c++操作符,用于a = b .* C,并将指向a、b和C对象的指针作为输入

C++ operator for a = b .* c with pointers to a,b, and c objects as input

本文关键字:对象 输入 指针 用于 操作符 c++      更新时间:2023-10-16

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

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

现在我想在MyClass中指定一个操作符,这样我就可以:

a = b*c;

所以a,b和c是已经存在的大对象,我不想再复制它们了。我想做乘法运算,然后直接写出结果a

1)这在c++操作符中是可能的吗?有人能给我一些语法上的提示吗?(我对操作符有点陌生…)

感谢您的帮助。

如果您将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

你真的不想这么做。坚持为值定义操作符的标准方式,而不是指针指向值,将使一切更清晰,更易于维护。

EDIT正如aschepler在评论中指出的那样,你甚至不能这样做。至少有一个实参必须是类类型或对类的引用。

如果您想避免大量的复制操作,您应该使用c++ 11移动语义或通过MoveProxy或Boost之类的东西模拟它们。支持库。

示例代码:

// 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(); }
};