课程和不可接受的成员
我很难理解如何修复此代码,我收到的错误消息是两个点:: x&点:: y是无法访问的。我该如何解决?
class Point {
int x, y;
public:
Point(int u, int v) : x(u), y(v) {}
int getX() { return x; }
int getY() { return y; }
void setX(int newX) { x = newX; }
void setY(int newY) { y= newY; }
};
int main() {
Point p(5, 3);
std::cout << p.x << ' ' << p.y;//should print out 5 3
return 0;
}
I am having a hard time understanding how to fix this code I get the error message that both point Point::x & Point::y are inaccessible. How do I fix this?
class Point {
int x, y;
public:
Point(int u, int v) : x(u), y(v) {}
int getX() { return x; }
int getY() { return y; }
void setX(int newX) { x = newX; }
void setY(int newY) { y= newY; }
};
int main() {
Point p(5, 3);
std::cout << p.x << ' ' << p.y;//should print out 5 3
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是数据成员
x
和y
是private
默认为类类型< /strong>使用关键字class
定义(与关键字struct
相反)。到 solve 您可以使用geters
getx
和gety
所示的错误,如下所示:demo 。
另一个选项(少/不建议)是制作
X
和y
public> public> public> struct 关键字和seters(setx
和sety
)。The problem is that the data members
x
andy
areprivate
by default for a class type defined using the keywordclass
(as opposed to keywordstruct
).To solve the error you can use the getters
getX
andgetY
as shown below:Demo.
Another option(less/not recommended) would be to make
x
andy
public or usestruct
keyword but that would defeat the purpose of having getters and setters(setX
andsetY
).类成员(与结构成员相反)默认为私有>点;但是,您已经为那些公开的值定义了getters。
Class members (as opposed to struct members) are private by default so you can't directly access
Point::x
andPoint::y
outside of the definition ofPoint
; however, you have defined getters for those values which are public.