2014-06-29 67 views
1

返回临时对象在头文件:无法从功能

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 
} 

看来,我不能把一个构造函数中返回线路。这是确定建立一个代码,但如果我把它放在回报,它会提供以下错误:

error: no matching function for call to ‘Point::Point(Point)’

,然后编译器会列出所有我的建设者。但是,嘿,它显然需要两个双重的论点,而不是一个Point类。那为什么呢?

而且我注意到,在由教授给出的示例代码,他们都很好:

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

Complex Complex::operator -() const 
{ 
    return Complex(- x, - y); 
} 
+0

您的副本构造函数不允许临时文件被复制。 – chris

+1

'Point(Point & A); //复制构造函数不是一个有用的复制构造函数,你需要'Point(const Point & A);''因为你不能从临时实例中复制 –

+1

'Point :: Point(double x,double y){//构造函数 X(x); Y(y);'使用初始化列表 – Manu343726

回答

0

这种说法

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

的问题是,有创建的临时对象。临时对象可能不会改变,因此使用它们作为参数的函数必须将相应的参数声明为常量引用而不是非常量引用。

声明拷贝构造函数如下方式

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

编译器将使用移动的构造。

+1

在这种情况下,请不要声明它。隐含的人会做正确的事情。 –

+0

@Mike Seymour对于文档的目的,如果类已经有其他显式的构造函数声明,则将其定义为默认值。 –

+0

没有人提到过这个,但代码失败的原因是*返回值*是函数内任何对象的独立的东西;它是从你“返回”的任何东西复制构建的。在第一种情况下,你的拷贝构造函数匹配;但在第二种情况下,您的副本构造函数不匹配(临时对象无法绑定到非常量引用),因此无法创建返回的值。 (这与调用operator-'无关)。 –

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

这是逐字的代码或改写?因为如此,这是完全废话。修复:

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

而且,你不需要手动定义拷贝构造函数,因为编译器将提供一个给你(用正确的签名),你想要做什么:复制数据成员。

+0

我解释并只在相应的代码中发布。我会添加更多的代码。我试过你的代码但遇到了同样的问题。此外,我只是因为我的技术援助表示这是强制性的,才使用该复制构造函数非常感谢,我学到了冒号的语法:) – Partita