【发布时间】:2013-06-27 09:47:07
【问题描述】:
让我们考虑以下代码:
class A{
public:
A(int x){}
};
class B{
public:
B(A a){};
};
int main() {
B b = 5;
return 0;
}
在编译编译器时抱怨:
/home/test/main.cpp:80: candidate constructor not viable: no known conversion from 'int' to 'A' for 1st argument
我不想创建 B(int) 构造函数 - 我希望编译器将此 int 隐式转换为 A 对象。
编辑:
直接初始化的工作方式如下:
B b(5);
可以改用赋值运算符吗?
【问题讨论】:
-
不,你不能隐含地这样做。
-
为什么我不能隐含地做到这一点?
-
尝试从 A 中添加赋值运算符,例如
B& operator = (const A& a);或B& operator = (A a);? -
是的,我已经尝试过了,但仍然出现同样的错误。
标签: c++ c++11 types compiler-construction type-conversion