簡體   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