c++操作符,用于a = b .* C,并将指向a、b和C对象的指针作为输入
C++ operator for a = b .* c with pointers to a,b, and c objects as input
我有三个指针指向三个对象:
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(); }
};
相关文章:
- 在构造函数中输入对象时C++类成员作用域
- 如何使用函数将一个对象的输入复制到另一个对象中
- 如何允许用户在对象和类中输入?
- 为什么复制构造函数不需要检查输入对象是否指向自身?
- C++ 通过输入创建对象
- 如何定义此"if block"中其他无效输入的值,以便在c ++中将字符串转换为对象?
- C++ 对象数组字符串输入在控制台上不起作用
- 删除函数环境中C++输入 R 对象
- 将私有对象变量与用户输入的变量进行比较
- 如何将用户输入从控制台传递到不同线程中的对象 -> QTcpsocket
- 流对象来表示文件输入,然后是标准输入?
- 使用用户的输入直接初始化对象的变量
- 有没有办法根据用户的输入访问类对象的信息?
- 是否可以保证输入<Type>实数时复杂对象的虚部设置为零?
- 使用非成员函数从输入流中提取类对象
- 如何使用ISTream对象输入多个字符到对象的数组中?(and 0作为哨兵值.下面的我的代码将无效)
- 将类对象输入到对象数组中
- 使用std ::函数或转发引用作为高阶函数的通用对象输入参数
- 对 C++ 中的对象输入数组进行排序
- 为什么函数中的对象输入不匹配但仍然有效