我非常喜欢让编译器为你做尽可能多的工作.在编写一个简单的类时,编译器可以为"free"提供以下内容:
operator=)但它似乎无法给你任何比较运算符 - 如operator==或operator!=.例如:
class foo
{
public:
std::string str_;
int n_;
};
foo f1; // Works
foo f2(f1); // Works
foo f3;
f3 = f2; // Works
if (f3 == f2) // Fails
{ }
if (f3 != f2) // Fails
{ }
Run Code Online (Sandbox Code Playgroud)
有这么好的理由吗?为什么执行逐个成员比较会成为问题?显然,如果类分配内存然后你要小心,但对于一个简单的类肯定编译器可以为你做这个?
struct A {
A(int) {}
};
struct B {
B(A) {}
};
int main() {
B b({0});
}
Run Code Online (Sandbox Code Playgroud)
构造出现b以下错误:
In function 'int main()':
24:9: error: call of overloaded 'B(<brace-enclosed initializer list>)' is ambiguous
24:9: note: candidates are:
11:2: note: B::B(A)
10:8: note: constexpr B::B(const B&)
10:8: note: constexpr B::B(B&&)
Run Code Online (Sandbox Code Playgroud)
我期待B::B(A)被召唤,为什么在这种情况下它是模棱两可的?