gpt4 book ai didi

c++ - 重载子类中的流插入运算符(<<)

转载 作者:行者123 更新时间:2023-11-30 03:53:54 29 4
gpt4 key购买 nike

我有一个 A 类,我为其定义了一个(重载的)流插入运算符。我从这个 A 类公开派生了一个 B 类,它有一个额外的数据成员。因此,我需要为派生类重新定义重载的流插入运算符,我是这样做的:

#include <iostream>

using namespace std;

class A {
int i;
char c;
public:
A(int i = 0, char c = ' ') {
this->i = i;
this->c = c;
}
friend ostream& operator << (ostream&, const 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&, const B&);
};

ostream& operator << (ostream& out, const A& a) {
out << "\nInteger: " << a.i << "\nCharacter: " << a.c << endl;
return out;
}

ostream& operator << (ostream& out, const B& b) {
out << b;
out << "\nDouble: " << b.d << endl;
return out;
}

int main() {
A a(10, 'x');
B b(20, 'y', 5.23);
cout << b;

return 0;
}

Question-1: Is this an appropriate technique of doing so? If not, kindly let me know where I'm going wrong.

Question-2: On running, this program crashes. Why so?

最佳答案

支持这一点的一种常见方法是让重载运算符调用虚成员函数:

class A { 
public:
virtual std::ostream &write(std::ostream &os) const {
// write self to os
os << "A\n";
return os;
}
};

class B : public A {
public:
virtual std::ostream &write(std::ostream &os) const {
// write self to os
// This can use the base class writer like:
A::write(os);
os << "B\n";
return os;
}
};

然后运算符重载只调用该成员函数:

std::ostream &operator<<(std::ostream &os, A const &a) {
return a.write(os);
}

write是虚拟的,你正在传递 A通过 (const) 引用,这会根据实际类型调用正确的成员函数(即,如果对象确实是 A::write 的实例,则调用 A,如果它是 B::write 的实例,则调用 B)。

例如,我们可以这样练习:

int main() { 
A a;
B b;

std::cout << a << "\n";
std::cout << b << "\n";
}

...产生这样的输出:

A

A
B

在实际使用中,您可能想要制作 write功能 protected ,并使 operator<< A的 friend .

关于c++ - 重载子类中的流插入运算符(<<),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29885672/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com