【问题标题】:C++ global scope classC++ 全局作用域类
【发布时间】:2015-11-21 21:19:13
【问题描述】:

我正在学习 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;
}

【问题讨论】:

    标签: c++ class scope namespaces global


    【解决方案1】:

    成员变量绑定到每个实例。所以你需要使用

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

    相反,test.y 也是如此。现在您使用的是test::x,它仅在成员变量为静态时才有效,即在您的类的所有实例之间共享。

    【讨论】:

      猜你喜欢
      • 2013-03-13
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2016-10-11
      相关资源
      最近更新 更多