如您所见,在两个实例上仅调用基类的流插入运算符的重载版本。我明白为什么会如此。这是因为没有动态绑定。但是,我该如何解决呢?
#include <iostream>
using namespace std;
class A {
int i;
char c;
public:
A(int i = 0, char c = ' ') {
this->i = i;
this->c = c;
}
int getI() { return i; }
char getC() { return c; }
friend ostream& operator << (ostream&, A&);
};
class B : public A {
double d;
public:
B(int i = 0, char c = ' ', double d = 0.0) : A(i, c), d(d) {}
friend ostream& operator << (ostream&, B&);
};
ostream& operator << (ostream& out, A& a) {
out << "\nInteger: " << a.i << "\nCharacter: " << a.c << endl;
return out;
}
ostream& operator << (ostream& out, B& b) {
out << "\nInteger: " << b.getI() << "\nCharacter: " << b.getC() << "\nDouble: " << b.d << endl;
return out;
}
int main() {
A* a = new A (10, 'x');
B* b = new B(20, 'y', 5.23);
A* array[] = { a, b };
cout << *(array[0]);
cout << "\n______________________________\n";
cout << *(array[1]);
delete a;
delete b;
cin.get();
return 0;
}
如何让cout << *(array[1]);
调用重载的流插入运算符,该运算符将B的对象作为其参数之一?
答案 0 :(得分:2)
您可以定义虚拟成员助手函数。
public void insert(String data)
{
Link link = new Link(data);
if(head == null)
{
head = link;
tail= link;
}
else
{
tail.next = link;
tail = link;
tail.next = head;
}
}
public void display()
{
// good implementation for display #2
while(head != null)
{
// System.out.println (head.data);
head = head.next;
}
}
你甚至不再需要2 class A {
public:
virtual void toStream(ostream& out) const {
out << "\nInteger: " << i << "\nCharacter: " << c << endl;
}
};
class B : public A {
public:
virtual void toStream(ostream& out) const {
out << "\nInteger: " << getI() << "\nCharacter: " << getC() << "\nDouble: " << d << endl;
}
};
ostream& operator << (ostream& out, const A& a) {
a.toStream(out);
return out;
}
。
对于operator<<()
,可以采取类似的技巧。
operator >> (istream& in, A& a)
答案 1 :(得分:0)
如果A
知道它将继承,您可以使用非虚拟接口:让操作员成为朋友,写一个受保护的(它不属于该类interface)执行写入的虚函数。