簡體   English   中英

無法從函數返回臨時對象

[英]Can't return a temporary object from function

在頭文件中:

class Point{
    public:
        Point();    // constructor
        Point(double x, double y);  // constructor
        Point(Point& A);    //Copy Constructor
        ~Point();   // destructor

        // below are the operator declarations. 
        Point operator - () const; // Negate the coordinates.

    private:
        double xCord;
        double yCord;

};

在Cpp實現文件中,相關的構造函數:

Point::Point(double x, double y){   // constructor
    X(x);// void X(double x) is a function to set the xCord 
    Y(y);// so is Y(y)

}

Point Point::operator-() const{ // Negate the coordinates.
    Point temp(-xCord,-yCord);
    return temp;
    // return Point(-xCord,-yCord); // cannot use this one
}

看來我不能將構造函數放在返回行中。 可以在代碼中構建一個,但是如果我把它放回去,它將給出以下錯誤:

錯誤:沒有匹配的函數調用'Point :: Point(Point)'

然后編譯器列出了我擁有的所有構造函數。 但是,顯然,它需要兩個雙重參數,而不是Point類。 那為什么呢?

我還注意到,在教授給出的示例代碼中,它們很好:

Complex::Complex(double dx, double dy)
{
    x = dx;
    y = dy;
}

Complex Complex::operator - () const
{ 
    return Complex(- x, - y);
}
Point::Point(double x, double y){   // constructor
    X(x);
    Y(y);
}

這是逐字代碼還是措辭釋義? 因為就目前而言,這完全是胡說八道。 固定:

Point::Point(double x, double y) : xCord(x), yCord(y)
{
}

另外,您不需要手動定義復制構造函數,因為編譯器將為您(具有正確的簽名)提供一個完全符合您想要的功能:復制數據成員。

這句話的問題

// return Point(-xCord,-yCord); // cannot use this one

是創建了一個臨時對象。 臨時對象可能不會更改,因此將它們用作參數的函數必須將相應的參數聲明為常量引用而不是非常量引用。

通過以下方式聲明復制構造函數

Point( const Point& A );    //Copy Constructor

或作為

Point( const Point& A ) = default;    //Copy Constructor

另一種方法是在不更改復制構造函數的情況下向類添加move構造函數。 例如

class Point{
    public:
        Point();    // constructor
        Point(double x, double y);  // constructor
        Point( Point& A);    //Copy Constructor
        Point( Point &&A ); // Move Constructor

在這種情況下

return Point(-xCord,-yCord);

編譯器將使用move構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM