gpt4 book ai didi

c++ - 如何为显式重载构造函数启用复制初始化?

转载 作者:行者123 更新时间:2023-11-28 05:41:46 26 4
gpt4 key购买 nike

我假设使重载的构造函数explicit 阻止复制初始化,如果我确实需要它是explicit 我怎样才能为下面的类启用复制初始化

class real {
public:
explicit real(const double& value) : x(value) {}
real(const real& other) : x(other.x) {}
~real() = default;

real& operator= (const double& rhs) {
this->x = rhs;
return *this;
}

operator double() {
return this->x;
}
private:
double x;
};

int main(){

real r1 = 3.4; // Error
real r2 = (real) 3.4; // Ok : is this the only way ?

return 0;
}

最佳答案

这不是好的 C++:

real r2 = (real) 3.4;

你要的是这个:

real r2(3.4);

这是在 C++ 中将参数传递给构造函数的常用方法。这就是人们在阅读您的代码时希望看到的内容。

如果你有需要分配的情况,你可以这样做:

r2 = real(3.4);

关于c++ - 如何为显式重载构造函数启用复制初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36954262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com