从函数返回对象时使用自定义复制构造函数的C ++?

时间:2015-06-06 10:48:01

标签: c++ constructor

class Tree
{
 private:
double height;
string name;

public:
Tree()
{
    cout << "Default constructor of class Tree." << endl;
    height = 0;
    name = "";
}

Tree(double he, string na)
{
    cout << "Parameterized constructor of class Tree." << endl;
    height = he;
    name = na;
}

Tree(Tree &t)
{
    cout << "Customized copy constructor of class Tree." << endl;
    height = t.height;
    name = t.name;
}

void toString()
{
    cout << name << " " << height << endl;
}
};
Tree getTree()
{
Tree t(321, "abc");
return t;
}

int main(int argc, char* argv[])
{
Tree t1(123, "xyz");
Tree t2 = getTree();
t2.toString();

return 0;
}

从函数getTree()返回的Tree对象应该使用自定义的复制构造函数复制到对象t2,而编译器抱怨&#34;错误:没有匹配函数来调用&#39; Tree :: Tree(Tree )&#39;&#34;

3 个答案:

答案 0 :(得分:2)

复制构造函数需要接受对象的const版本。将复制构造函数更改为:

Tree(const Tree &t)
{
    cout << "Customized copy constructor of class Tree." << endl;
    height = t.height;
    name = t.name;
}

清除错误。

答案 1 :(得分:-1)

c99.Game = (function(){ function Count99Game() { console.log("Count 99 game starts"); this.canvas = document.getElementById('game-canvas'); this.stage = new createjs.Stage(this.canvas); var totalTiles = 10; var tileOnPress = function(event) { console.log("Pressed"); this.stage.removeChild(event.target); this.stage.update(); }; for (var i = totalTiles; i > 0; i--) { var tile = new c99.Tile(i); this.stage.addChild(tile); tile.x = Math.random()*(this.canvas.width - tile.width); tile.y = Math.random()*(this.canvas.height - tile.height); //tile.onPress = (tileOnPress).bind(this); tile.addEventListener("click", tileOnPress.bind(this)); } this.stage.update(); } return Count99Game; })(); 调用复制构造函数t2 = getTree(),它接受​​对类Tree实例的引用,而函数Tree(Tree &t)返回一个对象,而不是引用。该问题的解决方案是函数Tree getTree()返回引用:Tree getTree()

只是为了您的信息,复制构造函数应该接受Tree& getTree(),这也解决了问题。编写这样的复制构造函数是一种常态:

const Tree &

编辑:您可能会收到一条警告,指出已返回对本地变量的引用,但您可以选择忽略警告,您可以更改复制构造函数。就个人而言,我会更改复制构造函数。

答案 2 :(得分:-1)

Tree getTree()
{
  Tree t(321, "abc");
  return t;
}

getTree(),这里按值返回一个本地对象。因此创建了一个临时对象(临时对象是const),这意味着Copy-Ctor正在传递一个const对象,而根据定义,它期望非const对象。将Copy-Ctor参数更改为const将解决此问题。