用C++编写一个简单的类

use*_*189 0 c++ private class

我收到一个错误,说我无法访问私人成员x和y.如何编写方法getX()和getY()以便它们可以看到x和y?谢谢.

#include <iostream>
#include <string>
using namespace 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;

}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 7

嗯,你已经书面getXgetY,你只需要使用它们:

cout << p.getX() << endl;
cout << g.getY();
Run Code Online (Sandbox Code Playgroud)

请注意,因为getX()并且getY()不修改您的类,它们应该是const:

class Point {
public:
    // ...

    int getX() const;
    int getY() const;

    // ...
};

// ...

int Point::getX() const {
    return x;
}

int Point::getY() const {
    return y;
}

// ...
Run Code Online (Sandbox Code Playgroud)