a = b。* c的C ++运算符,指向a,b和c对象作为输入

时间:2013-05-10 14:39:28

标签: c++ operator-overloading

我有三个指向三个对象的指针:

MyClass* a = new MyClass(...);
MyClass* b = new MyClass(...);
MyClass* c = new MyClass(...);

现在我想在MyClass中指定一个运算符,以便我可以这样做:

a = b*c;

所以a,b和c已经存在大型对象,我不想再制作任何副本。我想进行乘法并直接写出结果'a'。

1)这对c ++运算符来说是否可行?  2)有人能给我一些语法提示吗? (我对运营商来说有点新鲜......)

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

如果您为operator*撰写了MyClass

MyClass* a = new MyClass(...);
MyClass* b = new MyClass(...);
MyClass* c = new MyClass(...);

你应该像下面这样使用它:

*a = (*b) * (*c);

你不能用指针来做。例如,不可能

MyClass *operator*(const MyClass *a, const MyClass *b) // Impossible
{
 ...   
}

因为运算符定义必须具有MyClass的参数。

答案 1 :(得分:0)

你真的不想这样做。坚持使用标准值来定义操作符而不是指向值的指针将使一切变得更加清晰和易于维护。

编辑正如aschepler在评论中指出的那样,你甚至无法做到这一点。至少有一个参数必须是类类型或对类的引用。

如果要避免大量复制操作,则应使用C ++ 11移动语义或通过MoveProxyBoost.Move支持库等方式模拟它们。

示例代码:

// loads of memory with deep-copy
struct X {
  int* mem; 

  X() : mem(new int[32]) { }
  // deep-copy
  X(const X& other) 
    : mem(new int[32]) { std::copy(other.mem, other.mem+32, this.mem); }
  ~X() { delete[] mem; }
  X& operator=(const X& other) { std::copy(other.mem, other.mem+32, this.mem); return *this; }
  X(X&& other) : mem(other.mem) { other.mem = nullptr; }
  X& operator=(X&& other) { delete[] mem; this.mem = other.mem; other.mem = nullptr; return this; }

  friend void swap(const X& x, const X& y)
  { std::swap(x.mem, y.mem); }


  friend
  X operator*(const X& x, const X& y)
  { return X(); }
};