2011-03-23 88 views
0

我得到一个错误,说我不能访问私有成员x和y。如何编写方法getX()和getY(),以便他们可以看到x和y?谢谢。用C++编写一个简单的类

#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; 

} 
+0

你还缺少构造函数定义 – dcousens 2011-03-24 02:54:35

回答

7

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

cout << p.getX() << endl; 
cout << g.getY(); 

请注意,因为getX()getY()不会修改您的课程,所以它们应该是const

class Point { 
public: 
    // ... 

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

    // ... 
}; 

// ... 

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

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

// ... 
1

您不能访问x和y,因为它们是私人的。但是,你所做的getX和公众的getY,所以你的代码应该是这样的:

cout << p.getX() << endl; 
cout << g.getY(); 
string s; 
cin >> s; 
1

Point::getX()Point::getY()实际看到x分别y - 错误是在你的main,在那里你尝试直接访问它们,而不使用你为此目的准备的吸气剂。

cout << p.getX() << endl; 
1

好像你已经解决了自己编写函数的问题。现在,所有你需要做的就是改变你的main来调用这些函数:

// note the proper return type 
int main() { 
    Point p(5,5); 
    cout << p.getX() << endl; 
    // more code 
    return 0; 
} 
1

您的get_方法是正确的。问题是你没有在你的main功能中使用它们!试试这个:

cout << p.getX() << endl; 
+0

哦!咄!谢谢! – user620189 2011-03-23 20:16:42

2

它不应该是

cout << p.getX() << endl; 
cout << g.getY();