考虑这个例子:
class C {};
class B {
public:
B(C& c) : c_(c) {};
private:
C& c_;
};
class A {
public:
A(C& c) : b(c) {};
private:
B& b;
};
A
有引用成员(member)b
类B
. B
有一个引用类 C
的构造函数. A
的构造函数引用类 C
并尝试初始化 b
通过使用 c
调用后者的构造函数.
但是 clang 报错了以下信息:
wtf.cpp:12:13: error: non-const lvalue reference to type 'B' cannot bind to a value of unrelated type 'C'
A(C& c) : b(c) {};
^ ~
1 error generated.
听起来好像 clang 认为我正在分配 c
至 b
, 但我的意图是打电话 B
的构造函数 c
.我在这里做错了什么?
最佳答案
您所描述的不仅限于初始化列表,还包括通常的引用构造。以下不应编译:
class C
{};
class B
{
public:
B(C& c)
: c_(c)
{}
private:
C& c_;
};
int main()
{
C c;
B b0(c); // This works because you actually create an object of type B.
B& b1(c); // Error, cannot construct reference to B from C.
B& b2 = c; // Same as above, only a different notation.
// You cannot write a constructor of B to make these lines work,
// because you do not create an object of type B.
}
类 B
的对象可以从对 C
对象的引用构造,但引用不一样。只能从相同类型的对象或继承层次结构中低于类型的对象创建引用。
这正是引用的要点:您不构造对象。您只需为在其他地方创建的对象引入一个新名称。
关于c++ - 如何调用成员初始化列表中引用成员的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44754167/