C++全局作用域类

C++ global scope class

本文关键字:作用域 全局 C++      更新时间:2023-10-16

我正在学习c++,我制作了一个程序来使用类显示输入数字。我使用构造函数来初始化xy。程序运行良好,但我想使用全局范围来显示变量,而不是函数。注释行是我想要它做的,但它给了我一个错误,我尝试使用dublu::xdublu::y,但它说常量需要是static const。。。这是有效的,但对我来说不是一个解决方案。有什么想法吗?

#include <iostream>
using namespace std;
class dublu{
public:
    int x,y;
    dublu(){cin>>x>>y;};
    dublu(int,int);
void show(void);
};
dublu::dublu(int x, int y){
dublu::x = x;
dublu::y = y;
}
void dublu::show(void){
cout << x<<","<< y<<endl;
}
namespace second{
    double x = 3.1416;
    double y = 2.7183;
}
using namespace second;
int main () {
    dublu test,test2(6,8);
    test.show();
    test2.show();
    /*cout << test::x << 'n';
    cout << test::y << 'n';*/
    cout << x << 'n';
    cout << y << 'n';
    return 0;
}

成员变量以每个实例为界。所以你需要使用

cout << test.x << 'n';

并且类似地用于test.y。现在您正在使用test::x,它仅在成员变量为static时有效,即在类的所有实例之间共享。