繁体   English   中英

在构造函数 C++ 中调用另一个对象的方法

[英]Call another object's method in constructor C++

我试图从复制构造函数中调用 otherObjectArea 的 getter,并且我反驳了编译错误。 我这样做就像 Java。 我应该如何在 C++ 中正确执行?

class ObjectArea
{
private:
int x, y, width, height;

public:
ObjectArea(int x, int y, int width, int height)
{
    this->x = x;
    this->y = y;
    this->width=width;
    this->height = height;
}

ObjectArea():ObjectArea(0,0,0,0){}


ObjectArea(const ObjectArea &otherObjectArea){
    this->x = otherObjectArea.getX();
    this->y = otherObjectArea.getY();
    this->width = otherObjectArea.getWidth();
    this->height = otherObjectArea.getHeight();
}

int getX(){
    return this->x;
}

int getY(){
    return this->y;
}

int getWidth(){
    return this->width;
}

int getHeight(){
    return this->height;
}
};

编译错误:

ObjectArea.cpp:19:40: error: passing ‘const ObjectArea’ as ‘this’ argument discards qualifiers [-fpermissive]
   19 |         this->x = otherObjectArea.getX();
      |
                                        ^
ObjectArea.cpp:25:9: note:   in call to ‘int ObjectArea::getX()’
   25 |     int getX(){
      |         ^~~~

非常感谢。

您在const ObjectArea&引用上调用getX ,即对不得修改的 object 的引用。 但是, getX没有标记为const ,即您没有 promise ,该方法不会修改调用它的 object 。

通过将其更改为:

int getX() const {
    return this->x;
}

您将能够在const引用上调用getX 所有其他方法相同。

您正在从 const object 调用非 const function


class ObjectArea
{
private:
int x, y, width, height;

public:
ObjectArea(int x, int y, int width, int height)
{
    this->x = x;
    this->y = y;
    this->width=width;
    this->height = height;
}

ObjectArea():ObjectArea(0,0,0,0){}


ObjectArea(const ObjectArea &otherObjectArea){
    this->x = otherObjectArea.getX();
    this->y = otherObjectArea.getY();
    this->width = otherObjectArea.getWidth();
    this->height = otherObjectArea.getHeight();
}

int getX() const{
    return this->x;
}

int getY() const{
    return this->y;
}

int getWidth() const{
    return this->width;
}

int getHeight() const{
    return this->height;
}
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM