C++ 全局范围 class
C++ global scope class
我正在学习 C++,并且我使用 类 编写了一个程序来显示输入数字。
我使用构造函数来初始化 x
和 y
。该程序运行良好,但我想使用全局范围来显示变量而不是函数。
注释行是我想要它做的,但它给了我一个错误,我尝试使用 dublu::x
和 dublu::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 时有效,即在您的 class.
的所有实例之间共享
我正在学习 C++,并且我使用 类 编写了一个程序来显示输入数字。
我使用构造函数来初始化 x
和 y
。该程序运行良好,但我想使用全局范围来显示变量而不是函数。
注释行是我想要它做的,但它给了我一个错误,我尝试使用 dublu::x
和 dublu::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 时有效,即在您的 class.