面试题答案
一键面试重载流输出运算符 <<
和流输入运算符 >>
的方法
- 重载流输出运算符
<<
:- 通常将其定义为非成员函数(因为成员函数的第一个参数是
this
,不符合流输出运算符的使用习惯),为了访问类的私有成员,可以将其声明为友元函数。 - 函数原型一般为
ostream& operator<<(ostream& os, const ClassType& obj)
,其中os
是输出流对象,obj
是要输出的对象。返回ostream&
以便支持链式调用。
- 通常将其定义为非成员函数(因为成员函数的第一个参数是
- 重载流输入运算符
>>
:- 同样定义为非成员函数,也常声明为友元函数以便访问类的私有成员。
- 函数原型一般为
istream& operator>>(istream& is, ClassType& obj)
,其中is
是输入流对象,obj
是要输入数据的对象。返回istream&
以便支持链式调用。
性能优化点
- 对象传递方式:
- 在重载
<<
运算符时,对于要输出的对象,使用const &
传递,避免对象的拷贝,提高性能。例如在ostream& operator<<(ostream& os, const ClassType& obj)
中,obj
使用const &
传递。 - 在重载
>>
运算符时,对于要输入数据的对象,使用&
传递,因为要修改对象内容,同样避免不必要的拷贝。例如在istream& operator>>(istream& is, ClassType& obj)
中,obj
使用&
传递。
- 在重载
- 减少不必要的操作:在输入输出操作中,尽量减少复杂的计算和不必要的函数调用,只进行必要的数据读取和写入。
示例代码
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
// 重载流输出运算符 <<
friend std::ostream& operator<<(std::ostream& os, const Person& p) {
// 性能优化:使用 const & 传递对象,避免拷贝
os << "Name: " << p.name << ", Age: " << p.age;
return os;
}
// 重载流输入运算符 >>
friend std::istream& operator>>(std::istream& is, Person& p) {
// 性能优化:使用 & 传递对象,避免拷贝
is >> p.name >> p.age;
return is;
}
};
int main() {
Person p("", 0);
std::cout << "请输入姓名和年龄: ";
std::cin >> p;
std::cout << "输入的信息: " << p << std::endl;
return 0;
}
在上述代码中,operator<<
函数通过 const &
传递 Person
对象 p
,避免了对象拷贝,体现了性能优化措施。operator>>
函数通过 &
传递 Person
对象 p
,因为要修改对象内容,也避免了不必要的拷贝。