我正在尝试创建一个C++类,其行为与内置int类型完全相同,只有一个例外:调用operator*(或operator*=)的地方,而是调用addition.
起初,我班级的表现很差(内置int类型的1/2 ),但我注意到这是因为我忘了在下面包含复制构造函数:
struct AlmostInt {
AlmostInt () { }
AlmostInt (const AlmostInt &a) : val(a.val) { } // forgetting this killed
// performance
AlmostInt operator+(const AlmostInt &a) const { AlmostInt result = *this;
result.val += a.val;
return result; }
AlmostInt operator-(const AlmostInt &a) const { AlmostInt result = *this;
result.val -= a.val;
return result; }
AlmostInt operator*(const AlmostInt &a) const { AlmostInt result = *this;
result.val = result.val + a.val;
return result; }
AlmostInt &operator+=(const …Run Code Online (Sandbox Code Playgroud)