作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我假设使重载的构造函数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/
我是一名优秀的程序员,十分优秀!