c++ - C++中的构造函数重载

标签 c++

我的 C++ 重载没有像我认为的那样发挥作用:

#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。

我做错了什么?

最佳答案

Node(Game(),v); 在您的构造函数中并没有达到您的预期。它只是创建一个临时而不使用它并且没有任何效果。然后,当控制流过 ; 时,它会立即破坏该临时对象。

正确的方法是在每个构造函数中初始化成员。您可以在私有(private) init() 成员函数中提取它们的公共(public)代码,并在每个构造函数中调用它,如下所示:

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++ - C++中的构造函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7330296/

相关文章:

c++ - 不需要两个函数 for + 重载?

c++ - 编译时找不到Qt文件

c++ - 了解预处理器指令

C++ 头文件 #define Function(x) ('ABC\0' | ('0' +(x &0xFF)))

c++ - 连接由 C++ 中的类方法提供的字符串

c++ - 使用 C++ "for"命令计算指数的创建程序

c++ - C++ 中的结构

c++ - STL list::splice - 迭代器有效性

c++ - 编译器方差 : type of `this` when value-captured in mutable lambda defined in a const member function

c++ - 如何正确使用 C++ 强类型枚举?