课程和不可接受的成员

发布于 2025-01-28 06:40:12 字数 431 浏览 3 评论 0原文

我很难理解如何修复此代码,我收到的错误消息是两个点:: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红颜悴 2025-02-04 06:40:12

问题是数据成员xyprivate默认为类类型< /strong>使用关键字class定义(与关键字struct相反)。

solve 您可以使用geters getxgety所示的错误,如下所示:

 std::cout << p.getX() << ' ' << p.getY();

demo


另一个选项(少/不建议)是制作Xy public> public> public> struct 关键字和seters(setxsety)。

The problem is that the data members x and y are private by default for a class type defined using the keyword class(as opposed to keyword struct).

To solve the error you can use the getters getX and getY as shown below:

 std::cout << p.getX() << ' ' << p.getY();

Demo.


Another option(less/not recommended) would be to make x and y public or use struct keyword but that would defeat the purpose of having getters and setters(setX and setY).

A君 2025-02-04 06:40:12

类成员(与结构成员相反)默认为私有>点;但是,您已经为那些公开的值定义了getters。

Class members (as opposed to struct members) are private by default so you can't directly access Point::x and Point::y outside of the definition of Point; however, you have defined getters for those values which are public.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文