c++中的多态加号
Polymorphic plus sign in C++?
我了解多态和继承如何在c++中工作,但我的问题是:如何使操作符多态为以下具体示例?
假设我有一个Foo类和两个Foo实例,fooA和fooB。我想重新定义加号操作符,以便"fooA + fooB;"执行特定于Foo实例的操作(无论该操作是什么)。函数原型是什么样子的?这让我很困惑,因为我习惯了以字母开头的函数…如有任何帮助,我将不胜感激。
顺便说一下,这不是一个家庭作业问题——更像是一个奇迹(我正在考虑Ruby中的多态性)。
示例来自http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/cplr318.htm:
#include <iostream>
using namespace std;
class complx
{
double real, imag;
public:
complx(double real = 0., double imag = 0.); // constructor
complx operator+(const complx&) const; // operator+()
};
// define constructor
complx::complx(double r, double i)
{
real = r; imag = i;
}
// define overloaded + (plus) operator
complx complx::operator+(const complx& c) const
{
complx result;
result.real = this->real + c.real;
result.imag = this->imag + c.imag;
return result;
}
int main()
{
complx x(4,4);
complx y(6,6);
complx z = x + y; // calls complx::operator+()
}
const Foo operator+(const Foo& a, const Foo& b)
为正确签名。如果数据是私有的,并且没有mutator函数(即"setter"),则它需要是友元函数。
操作符应该是全局函数而不是成员,以便将第一个形参强制为您的类型。例如,如果int
可以被强制为Foo
,那么使用上面的签名是合法的:1 + foo
.
编辑:代码演示为什么操作符+应该是全局的…
struct Foo {
int i;
Foo(int i) : i(i) {}
const Foo operator+(const Foo& a) {
return Foo(this->i + a.i);
}
};
int main() {
Foo f(5);
f + 1;
1 + f; // g++ 4.5 gacks here.
return 0;
}
错误如下:
main.cpp: In function ‘int main()’:
main.cpp:14:9: error: no match for ‘operator+’ in ‘1 + f’
对于二进制+
,您需要某种形式的双分派,而不是由c++开箱支持。有几种实现方法这些都有各种各样的缺点。不管你怎么实现双调度本身,对于n不同的派生类型,您将需要n2不同的函数
相关文章:
- 多态性和功能结合
- 具有默认模板参数的多态类的模板推导失败
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 多态二进制函数
- 访问存储在向量C++中的结构的多态成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 将 std::allocate_shared 与多态资源分配器一起使用
- 通过switch和static_cast访问多态对象的运行时类型
- C++boost序列化多态性问题
- 多态杆件变量 - 类设计
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- Doees the 'this' 指针参与虚函数的多态行为
- C++ 在堆栈中包含多态属性的类对象存储
- 基类和派生类的多态赋值运算符
- 转身多态对象
- 如何在基类指针向量的元素上应用重载的多态函数
- 具有智能指针的多态性
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- C++事件系统 - 多态事件和事件处理程序