如何在子类中重写父类的重载运算符+函数?
其中父类是个抽象类,它的重载运算符+函数是个纯虚函数。
class Father
{
public:
virtual Father* operator+(Father*) = 0;
};
class Son:public Father
{
public:
Son(int a, int b) {
this->a= new int(a);
this->b= new int(b);
}
Father* operator+(Father* other) {
//此处如何书写?
}
private:
int *a= nullptr;
int *b= nullptr;
};
int main() {
Father* son1 = new Son(1, 2);//图形1
Father* son2 = new Son(3, 4);//图形2
auto son3=son1+
son2 ; //报错,无法实现
}
class Father
{
public:
virtual Father* operator+(Father*) = 0;
};
class Son:public Father
{
public:
Son(int a, int b) {
this->a= new int(a);
this->b= new int(b);
}
Father* operator+(Father* other) {
Son *p = (Son*)other;
*a += *(p->a);
*b += *(p->b);
return this;
}
private:
int *a;
int *b;
};
int main() {
Father* son1 = new Son(1, 2);//图形1
Father* son2 = new Son(3, 4);//图形2
auto son3=*son1+son2 ;
return 0;
}
啥乱七八糟的
虚函数机制,是基于引用或者指针调用才能实现
举例说明就是
class A{
public:
virtual void test();
}
class B:A{
void test()
}
A* a=new B;
a->test();//这里才引发多
A a,b;
a+b//这里是值类型操作,不能用虚拟机制
operator+ 必须是值类型相加,所以直接在对象上调用,无法达到效果其次参数不对
operator+参数一般是const T&
首先你那样写的话?想干嘛?指针跟指针加?
理论上,你是想对象中的成员进行运算,所以你的operator 应该针对对象,而不是对象的指针。