小编Fum*_*Eda的帖子

自定义C++类可以复制内置类型的性能吗?

我正在尝试创建一个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)

c++ embedded stack operator-overloading

14
推荐指数
1
解决办法
441
查看次数

标签 统计

c++ ×1

embedded ×1

operator-overloading ×1

stack ×1