C++派生类和基类函数重载
有时候派生类和基类重载同一个友元函数,那么在子类中的重载函数应该怎么写呢
class Parent{
private:
int a, b;
public:
Parent(int x, int y){
a = x;
b = y;
}
friend ostream& operator<<(ostream &os, Parent &p){
os << "a: "<<p.a<<" b: "<<p.b;
return os;
}
};
//子类也重载了 >> 操作符,希望调用父类的成员函数
class Child: public Parent{
private:
int c;
public:
Child(int x, int y, int z):Parent(x, y)
{
c = z;
}
friend ostream& operator<<(ostream &os, Child &c){
// ****** //
return os;
}
};
这一段应该怎么写,如何分离出父类这部分。因为基类和派生类重载了同一个函数,无法在子类中直接调用,否则会无限循环调用自身。
解决办法是,重用尽量都在成员函数中实现,友元函数就不要想重用了。
class Parent{
private:
int a, b;
public:
Parent(int x, int y){
a = x;
b = y;
}
ostream & disc(ostream& os){
os << "a: "<<a<<" b: "<<b;
return os;
}
friend ostream& operator<<(ostream &os, Parent &p){
p.disc(os);
return os;
}
};
class Child: public Parent{
private:
int c;
public:
Child(int x, int y, int z):Parent(x, y)
{
c = z;
}
void disc(ostream &os){
Parent::disc(os);
cout<<" c: "<<c;
}
friend ostream& operator<<(ostream &os, Child &co){
co.disc(os);
cout << co.c;
return os;
}
};