MikerNO_8 2024-02-29 09:12 采纳率: 0%
浏览 2

关于静态变量的两个个问题

为什么main函数输出的n是0?static修饰的n为什么可以在其他文件中使用?

img


/*main.cpp*/ 
#include "Cat.h"
#include <iostream>

using namespace std;

void main(){
    fn1();
    n=n+1; 
    cout<<n<<endl; 
    fn1();
    fn1();
    fn1();
    fn1();
    fn1();
    fn1();
    cout<<n<<endl; 
} 
/*Cat.h*/ 
class Cat{
    int id;
    static int count;
public:
    Cat(int id):id(id){
        count++;
    }
    Cat(const Cat &c);
    ~Cat();
    int getId();
    static int getCount();
};
/*问题相关代码片段*/
static int n=0;

void fn1();
/*Cat.cpp*/ 
#include "Cat.h"
#include <iostream>

using namespace std;

int Cat::count=0;

int Cat::getCount(){
    return count;
}

Cat::Cat(const Cat &c){
    count++;
    id=count;
}

Cat::~Cat(){
    count--;
}

int Cat::getId(){
    return id;
}
/*问题相关代码片段*/
void fn1(){
    n=n+1;
    cout<<n<<endl;
}
  • 写回答

4条回答 默认 最新

  • MikerNO_8 2024-02-29 11:04
    关注

    直接输出地址发现main函数的n和静态变量n是同一个而fn1函数里的n不是,但是程序我觉等应该报错才对呀?首先是无论是main函数还是fn1都不能用到其他文件用static修饰的变量,其次fn1怎么莫名奇妙自己生成了一个变量n呢?

    img

    /*main.cpp*/ 
    #include "Cat.h"
    #include <iostream>
     
    using namespace std;
    
    //extern int n;
    
    void main(){
        fn1();
        n=n+1; 
        cout<<"main n is:"<<&n<<endl; 
        fn1();
        fn1();
        fn1();
        fn1();
        fn1();
        fn1();
        cout<<"main n is:"<<&n<<endl;  
        Cat c(1);
        c.showNaddress();
    } 
    
    
    /*Cat.h*/ 
    #include <iostream>
    
    static int n=0;
    
    class Cat{
        int id;
        static int count;
    public:
        Cat(int id):id(id){
            count++;
        }
        Cat(const Cat &c);
        ~Cat();
        int getId();
        static int getCount();
        //输出 static n地址 
        void showNaddress(){
             cout<<"static n is:"<<&n<<endl; 
         }
    };
     
    void fn1();
    
    
    /*Cat.cpp*/ 
    #include "Cat.h"
    #include <iostream>
     
    using namespace std;
     
    int Cat::count=0;
     
    int Cat::getCount(){
        return count;
    }
     
    Cat::Cat(const Cat &c){
        count++;
        id=count;
    }
     
    Cat::~Cat(){
        count--;
    }
     
    int Cat::getId(){
        return id;
    }
    
    /*问题相关代码片段*/
    void fn1(){
        n=n+1;
        cout<<"fn1 n is:"<<&n<<endl; 
    }
    
    
    评论

报告相同问题?

问题事件

  • 修改了问题 2月29日
  • 创建了问题 2月29日

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题