Reputation: 141
I'm learning c++ and I make a program to show input numbers using classes.
I used constructors to initialize the x
and y
. The program works fine but I wanted to use the global scope to show the variables instead of a function.
The commented lines is what I wanted it to do but it gives me an error, I tried instead using dublu::x
and dublu::y
but it says that constants need to be static const
... this works but it's not a solution for me. Any ideas?
#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;
}
Upvotes: 0
Views: 467
Reputation: 56557
The member variables are bounded to each instance. So you need to use
cout << test.x << '\n';
instead, and similarly for test.y
. Right now you are using test::x
, which works only if the member variable is static, i.e. is shared among all instances of your class.
Upvotes: 2