C++全局作用域类
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时有效,即在类的所有实例之间共享。
相关文章:
- 全局作用域中函数指针的赋值
- 不同作用域中的静态变量和全局变量
- 在编译时选择全局作用域函数
- 在c++中,全局作用域中只允许"表达式"初始化全局对象.我在哪里可以在标准中找到这个
- 用LD_PRELOAD和C++中的全局作用域对象加载堆分析器
- 是头文件全局作用域中的变量
- C++全局整数和作用域整数初始值
- 线程静态类方法与全局作用域
- C++全局作用域类
- 全局变量和枚举之间的作用域问题
- 全局作用域中匿名命名空间中的Can名称具有前导下划线
- 控制对c++全局作用域的访问
- 在iPhone xcode应用程序中,是否可以声明一个具有全局作用域的指针?
- 将Javascript函数添加到全局作用域
- c++中如何初始化全局作用域的静态成员
- 如何使.h中创建的变量成为程序的全局作用域
- 线程局部全局作用域变量
- 全局作用域枚举和命名空间冲突
- c++访问上层作用域而不是全局作用域
- 构造函数排序(全局作用域)问题