Writing a simple class in C++
I am getting an error saying that I can't access private members x and y. How do I write the methods getX() and getY() so that they could see x and y? Thanks.
#include <iostream>
#include <string>
using namespac开发者_JAVA百科e std;
class Point {
public:
Point(int x, int y);
Point();
int getX();
int getY();
private:
int x, y;
};
int Point::getX() {
return x;
}
int Point::getY() {
return y;
}
void main () {
Point p(5,5);
Point g;
cout << p.x << endl;
cout << g.y;
string s;
cin >> s;
}
Um, you already have written getX
and getY
, you just need to use them:
cout << p.getX() << endl;
cout << g.getY();
Note that, because getX()
and getY()
don't modify your class, they should be const
:
class Point {
public:
// ...
int getX() const;
int getY() const;
// ...
};
// ...
int Point::getX() const {
return x;
}
int Point::getY() const {
return y;
}
// ...
Shouldn't it be
cout << p.getX() << endl;
cout << g.getY();
You can't access x and y, as they're private. However, you've made getX and getY public, so your code would look like this:
cout << p.getX() << endl;
cout << g.getY();
string s;
cin >> s;
Point::getX()
and Point::getY()
actually see x
respectively y
- the error is in your main
, where you try to access them directly, without using the getters you made exactly for this purpose.
cout << p.getX() << endl;
Seems like you've solved the problem of writing the functions yourself. Now all you have to do is change your main
to call those functions:
// note the proper return type
int main() {
Point p(5,5);
cout << p.getX() << endl;
// more code
return 0;
}
Your get_
methods are correct. The problem is that you are not using them in your main
function! Try this:
cout << p.getX() << endl;
精彩评论