无法从函数返回临时对象

Par*_*ita 1 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;

};
Run Code Online (Sandbox Code Playgroud)

在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
}
Run Code Online (Sandbox Code Playgroud)

似乎我不能在返回行中放置构造函数.在代码中构建一个是可以的,但如果我把它放在返回中,它将给出以下错误:

错误:没有匹配函数来调用'Point :: Point(Point)'

然后编译器列出我拥有的所有构造函数.但是,嘿,它显然需要两个双重参数,而不是Point类.那为什么呢?

我也注意到,在教授给出的示例代码中,他们很好:

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

Complex Complex::operator - () const
{ 
    return Complex(- x, - y);
}
Run Code Online (Sandbox Code Playgroud)

fre*_*low 7

Point::Point(double x, double y){   // constructor
    X(x);
    Y(y);
}
Run Code Online (Sandbox Code Playgroud)

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

Point::Point(double x, double y) : xCord(x), yCord(y)
{
}
Run Code Online (Sandbox Code Playgroud)

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