首页 > 解决方案 > 在构造函数 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(){
      |         ^~~~

非常感谢。

标签: c++

解决方案


您正在调用引用,即getXconst ObjectArea&不得修改的对象的引用。但是,getX没有标记为const,即,您不保证该方法不会修改调用它的对象。

通过将其更改为:

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

您将能够调用getX参考const。所有其他方法相同。


推荐阅读