构造函数在C ++中重载 [英] Constructor Overloading in C++
问题描述
我的C ++重载不会像我假设的那样:
My C++ overloading does not act as I assume it should:
#include "Node.h"
#include <iostream>
Node::Node()
{
cout << "1" << endl;
Node(Game(), 0.0);
}
Node::Node(double v)
{
cout << "2" << endl;
Node(Game(),v);
}
Node::Node(Game g, double v)
{
cout << "3" << endl;
numVisits = 0;
value = v;
game = g;
}
输出:
Node n(16);
cout << n.value << endl;
为0,当它应为16时。
is 0, when it should be 16.
我做错了什么?
推荐答案
Node / code>在你的构造函数不做你所期望的。它只是创建一个临时没有使用它,并没有效果。然后,当控制流过时,它立即销毁该临时。
Node(Game(),v);
in your constructor doesn't do what you expected. It just creates a temporary without using it and makes no effect. Then it immediately destructs that temporary when control flows over the ;.
正确的方式是初始化每个构造函数中的成员。你可以在私有的init()成员函数中提取它们的公共代码,并在每个构造函数中调用它,如下所示:
The correct way is initializing the members in each constructor. You could extract their common code in a private init() member function and call it in each constructor like the following:
class Foo {
public:
Foo(char x);
Foo(char x, int y);
...
private:
void init(char x, int y);
};
Foo::Foo(char x)
{
init(x, int(x) + 3);
...
}
Foo::Foo(char x, int y)
{
init(x, y);
...
}
void Foo::init(char x, int y)
{
...
}
C ++ 11将允许构造函数调用其他对等构造函数(称为 delegation ),但是,大多数编译器尚未支持。
C++11 will allow constructors to call other peer constructors (known as delegation), however, most compilers haven't supported that yet.
这篇关于构造函数在C ++中重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!