【发布时间】:2021-12-28 23:12:46
【问题描述】:
我在下面的代码中提出了一个意外行为(据我个人所知),它不尊重默认的成员初始化值。我有一个单一参数赋值的承包商,它假设从赋值运算符构建类。我忘记使用正确的参数名称,最终遇到了这个问题(请参阅带有故意错误的单参数构造函数的行:
为什么我得到垃圾值而不是成员初始化值?
我自己的假设是因为模板类,0 与 0.0 不一样...但尝试使用 并得到同样的问题。
#include <iostream>
#include <concepts>
template <class T>
requires std::is_arithmetic_v<T>
class Complex
{
private:
T re = 0;
T im = 0;
public:
Complex() {
std::cout << "Complex: Default constructor" << std::endl;
};
Complex(T real) : re{re} { // should be re{real}, but why re{re} is not 0?
std::cout << "Complex: Constructing from assignement!" << std::endl;
};
void setReal(T t) {
re = t;
}
void setImag(const T& t) {
im = t;
}
T real() const {
return re;
}
T imag() const {
return im;
}
Complex<T>& operator+=(const Complex<T> other) {
re+= other.re;
im+= other.im;
return *this;
}
bool operator<(const Complex<T>& other) {
return (re < other.re && im < other.im);
}
};
int main() {
Complex<double> cA;
std::cout<< "cA=" << cA.real() << ", " << cA.imag() << "\n";
Complex<double> cB = 1.0; // Should print "1.0, 0" but prints garbage
std::cout<< "cB=" << cB.real() << ", " << cB.imag() << "\n";
Complex<int> cC = 1;
std::cout<< "cC=" << cC.real() << ", " << cC.imag() << "\n";
return 0;
}
示例输出:
复数:默认构造函数 cA=0, 0 复杂:从赋值构造! cB=6.91942e-310, 0 复杂:从赋值构造! cC=4199661, 0
CompilerExplorer上的代码。
【问题讨论】: