【发布时间】:2020-08-18 18:29:38
【问题描述】:
我有以下代码:
#include <iostream>
struct A {
A(int x=1, int y=1) : x(x), y(y) { }
A(const A& other) : x(other.x), y(other.y) { }
operator bool() const { return !x && !y; }
friend std::ostream& operator<<(std::ostream& os, const A& a) {
os << a.x << "," << a.y << "\n";
return os;
}
int x;
int y;
};
int main(int argc, char const *argv[]) {
A const A10x10(10, 10);
A a;
std::cout << a;
A aa = A10x10;
std::cout << aa;
return 0;
}
以上打印:
1,1
10,10
当我将复制构造函数更改为显式(即explicit A(const A& other);)时,我得到:
1,1
0,1
我在(显式)复制构造函数中放置了一个打印语句,实际上它没有被调用。为什么会这样? explicit 有什么不同?
我使用的是 C++17,用 Clang10 编译。
【问题讨论】:
-
这是一个错字
A::A() : x(x), y(y) {}(缺少参数)吗?如果没有,你有 UB。 -
你能提供一个minimal reproducible example吗?如果你明确复制构造函数,你的代码应该编译失败......不仅仅是没有被调用或做其他事情。
-
实际上,我看到的恰恰相反。
10,10隐式时,0,1显式时。 -
将
A aa = A::A10x10;这一行更改(或添加aaa版本)为bool temp = A::A10x10; A aa = temp;现在你明白了吗?
标签: c++ constructor c++17 copy-constructor