c++ - 构造函数调用问题

标签 c++ c++11 c++14 c++builder

在这段代码中,当尝试创建 dobj4 时出现编译错误

#include<iostream>
using namespace std;
class mod;
class  name {
    friend mod;
    public:
            name(const char* n) {
                    cout << "1 arg constructor for name\n";
            }
            name() {
                    cout << "no arg constructor for name\n";
            }
            name(const char* n, int i ){
                    cout << "2 arg constructor for name\n";
            }
      };

class mod {
    public:
    mod() {
            cout << "base class constructor invoked\n";
    }
};

struct derived : mod {

    derived(name) {
            cout << "derived constructor invoked\n";
    }
 };

int main() {
    name nobj;
    derived dobj(nobj);

    name nobj1("hello");
    derived dobj1(nobj1);

    derived dobj2("Hi");

    name nobj2("yo", 2);
    derived dobj3(nobj2);

 //      derived dobj4("go", 4);

    return 0;
}

需要了解在 dobj2 的情况下传递字符串如何调用名称的构造函数,但在 dobj4 的情况下它会导致错误。 如何解决这个问题?

最佳答案

转换构造函数的规则在 C++03C++11 中有所不同。

C++03 中:只有一个参数的构造函数,或者在多个参数的情况下,其余参数都具有默认值,可以隐式转换。

例子:

name(const char* n) {}
name(int n, int i = 0) {} // i has a default value

C++11 中:在上面的 C++03 中定义的所有情况以及具有多个参数的构造函数。但是这样的构造函数调用需要大括号初始化

例子:

derived dobj4({"go", 4}); // call to name(const char* n, int i) is brace-initialized

不用说,如果构造函数被声明为explicit,它就不会被转换。

关于c++ - 构造函数调用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46047436/

相关文章:

c++ - 隐藏 C++ 库的私有(private)成员

c++ - 转换到同一类型

c++ - C++ 中的类模板和友元

c++ - 如何正确初始化 C++11 std::seed_seq

c++ - 编译器优化破坏代码

c++ - 绕过显式特化的标准限制

c# - 随机二进制生成器(非伪)

c++ - 使用模板有条件地生成 C++ 类的数据成员

c++ - 了解提案 N3650 for C++1y 中有关可恢复函数的示例

c++ - 如何将函数参数传递给 boost::async()