相关疑难解决方法(0)

为什么C++编译器没有定义operator ==和operator!=?

我非常喜欢让编译器为你做尽可能多的工作.在编写一个简单的类时,编译器可以为"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)

有这么好的理由吗?为什么执行逐个成员比较会成为问题?显然,如果类分配内存然后你要小心,但对于一个简单的类肯定编译器可以为你做这个?

c++ operators

286
推荐指数
11
解决办法
8万
查看次数

使用列表初始化调用Ambigous构造函数

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)被召唤,为什么在这种情况下它是模棱两可的?

c++ c++11 list-initialization

13
推荐指数
1
解决办法
801
查看次数

标签 统计

c++ ×2

c++11 ×1

list-initialization ×1

operators ×1