如何制作这个指针向量然后正确打印de Derived1对象和Derived2对象?
即使我加入"<<"运算符在派生类中,似乎使用了基类运算符。我不能让操作员虚拟,因为他们不是班级的成员,他们是朋友。
我该怎么做才能使程序采用"<<"来自Derived1类或Derived2类的运算符,此外,使用:
打印Base类的东西out << (Base&)temp;
在我的运营商定义中。
#include<iostream>
#include<fstream>
using namespace std;
class Base {
private:
int base;
public:
Base() :base(10){}
friend ostream& operator<<(ostream& out, const Base& temp)
{
out << "======== BASE ========" << endl;
out << temp.base << endl;
out << "======== BASE ========" << endl;
return out;
}
friend ofstream& operator<<(ofstream& out, const Base& temp)
{
out << "======== BASE ========" << endl;
out << temp.base << endl;
out << "======== BASE ========" << endl;
return out;
}
};
class Derived1 :public Base {
private :
int derived1;
public:
Derived1() :derived1(5){}
friend ostream& operator<<(ostream& out, const Derived1& temp)
{
out << (Base&)temp;
out << "======== DERIVED1 ========" << endl;
out << temp.derived1 << endl;
out << "======== DERIVED1 ========" << endl;
return out;
}
friend ofstream& operator<<(ofstream& out, const Derived1& temp)
{
out << (Base&)temp;
out << "======== DERIVED1 ========" << endl;
out << temp.derived1 << endl;
out << "======== DERIVED1 ========" << endl;
return out;
}
};
class Derived2 :public Base {
private:
int derived2;
public:
Derived2() :derived2(5) {}
friend ostream& operator<<(ostream& out, const Derived2& temp)
{
out << (Base&)temp;
out << "======== DERIVED2 ========" << endl;
out << temp.derived2 << endl;
out << "======== DERIVED2 ========" << endl;
return out;
}
friend ofstream& operator<<(ofstream& out, const Derived2& temp)
{
out << (Base&)temp;
out << "======== DERIVED2 ========" << endl;
out << temp.derived2 << endl;
out << "======== DERIVED2 ========" << endl;
return out;
}
};
void main()
{
Derived1 d1;
Derived2 d2;
Base* v[2];
v[0] = &d1;
v[1] = &d2;
cout << *v[0] << endl;
ofstream f("fis.txt");
f << *v[0];
}
答案 0 :(得分:1)
显示的代码有几个问题
1)没有必要为std :: ostream和std :: ofstream定义单独的运算符(这在其中一条注释中有注明)
由于std::ostream
是std::ofstream
的超类,因此只需要为std::ostream
实现运算符。
2)“using namespace std”is always the wrong thing to do。
3)main()函数should return an int。
现在,回答这里的主要问题,这里需要做的就是采用虚拟继承。这就是虚拟继承的用途。你知道的。现在,仅仅因为操作员不能是虚拟的,正如你所指出的那样,绝对没有法律阻止他们自己调用虚方法。
Base
的{{1}}应该只是一些适当命名的函数的外观,例如format(),它将作为类中的虚方法实现。
最终结果如下:
operator<<
答案 1 :(得分:0)
由于你不能使流操作符工作,因为它不是成员函数所以不能虚拟,你必须创建另一个虚拟函数,并从基类的流操作符调用它。
你可以称之为virtual void print()