无法从函数返回临时对象

时间:2014-06-29 12:58:48

标签: c++

在头文件中:

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);
}

2 个答案:

答案 0 :(得分:7)

Point::Point(double x, double y){   // constructor
    X(x);
    Y(y);
}

这是逐字的代码还是转述?因为它的立场,完全是胡说八道。修正:

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

此外,您不需要手动定义复制构造函数,因为编译器将为您提供一个(具有正确的签名),完全符合您的要求:复制数据成员。

答案 1 :(得分:0)

此声明的问题

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

是创建了一个临时对象。临时对象可能不会被更改,因此使用它们作为参数的函数必须将相应的参数声明为常量引用而不是非const引用。

以下列方式声明复制构造函数

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

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

另一种方法是在不更改复制构造函数的情况下向类中添加移动构造函数。例如

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);

编译器将使用移动构造函数。

相关问题