C++ 是否应该在赋值时调用构造函数?
VS2015中以下代码的输出为“构造函数” 它不应该因为缺少赋值运算符而无法编译吗C++ 是否应该在赋值时调用构造函数?,c++,C++,VS2015中以下代码的输出为“构造函数” 它不应该因为缺少赋值运算符而无法编译吗 struct A { }; struct B { B(){} B(const A& a) { cout << "constructor" << endl; } //B& operator=(const A& a) { // cout << "assignment operator" <&
struct A { };
struct B {
B(){}
B(const A& a) {
cout << "constructor" << endl;
}
//B& operator=(const A& a) {
// cout << "assignment operator" << endl;
// return *this;
//}
};
int main() {
A a;
B b;
b = a;
return 0;
}
struct A{};
结构B{
B(){}
B(施工A&A){
cout是的,当转换正在进行时,比如在您的测试用例中
你实际上是在打电话
b = B(a);
因为B
的赋值运算符B&operator=(B const&)
是隐式声明的,所以在重载解析期间可以找到它。因为您的赋值距离匹配只有一次转换(这正是允许发生的转换数)它将<代码> a <代码>转换为<代码> b>代码>,然后将新的临时代码代码>分配给<代码> b>代码> 让我们考虑一个类似的例子。
double a;
int b=5;
a=b;
唯一可以分配给double
的是另一个double
。但是,int
可以转换为double
与此类似,A
可以转换为B
,因为这样做的构造函数存在。这就是发生的情况。您的代码隐式地从A
转换为B
,B=A
编译为B=B(A);
。如果您想将其检测为错误,可以使用:
在此之后,构造函数将永远不会被隐式调用,如果您想调用它,您必须显式地编写它:b=b(a)
这对你很有用:但它们不能处理任何转换,比如从A到B,对吗?哦,我现在看到了,我以为它是B从A继承的。抱歉。在这种情况下,我觉得有点奇怪。这可能是编译器的问题。你可以将int
分配给double
这种定义的行为是,int
被隐式转换为double
,转换的结果替换了double
的存储值。也许最好说“可以存储在double
变量中的唯一东西是double
值”很好地提到了explicit
关键字
struct B {
B(){}
explicit B(const A& a) {
std::cout << "constructor" << std::endl;
}
};
prog.cpp: In function 'int main()':
prog.cpp:20:7: error: no match for 'operator=' (operand types are 'B' and 'A')
b = a;
^
prog.cpp:5:8: note: candidate: B& B::operator=(const B&)
struct B {
^
prog.cpp:5:8: note: no known conversion for argument 1 from 'A' to 'const B&'
prog.cpp:5:8: note: candidate: B& B::operator=(B&&)
prog.cpp:5:8: note: no known conversion for argument 1 from 'A' to 'B&&'