1. 重载
C++的iostream
库和C中的stdio
库中分别的cout/cin
和printf/scanf
相比有哪些优势呢?
- 首先是类型处理更加安全和智能,我们无须应对
%d、%f
- 而且扩展性极强,对于新定义的类,
printf
想要输入输出一个自定义的类的成员是天方夜谭的,而iostream
中使用的位运算符都是可重载的 - 并且可以将清空缓冲区的自由交给了用户,而且流风格的写法也更加自然和简洁。
#include <iostream>
#include <string>
using namespace std;
class stu{
public:
int age;
int score;
string name;
stu(int age,int score,string name):age(age),score(score),name(name){}
friend ostream& operator << (ostream & os, stu& s){
os << s.age << ' ' << s.score << ' ' << s.name << endl;
return os;
}
friend istream& operator >> (istream& is, stu& s){
cin >> s.age >> s.score >> s.name;
return is;
}
};
int main(){
srand(unsigned int(time(NULL)));
stu s1(24, 100, "wjh");
cout << s1;
stu s2(1,1,"as");
cin >> s2;
cout << s2;
system("pause");
return 0;
}
2. friend友元函数
在重载ostream
重载运算符<<
的时候,需要使用到friend友元函数
,因为可能会访问stu
对象的私有函数成员,需要访问权限。
当不使用友元函数的时候,这个函数就是成员变量。
实例:
#include <iostream>
using namespace std;
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// 成员函数定义
void Box::setWidth( double wid )
{
width = wid;
}
void printWidth( Box box )
{
/* 因为 printWidth() 是 Box 的友元,它可以直接访问该类的任何成员 */
cout << "Width of box : " << box.width <<endl;
}
int main( )
{
Box box;
// 使用成员函数设置宽度
box.setWidth(10.0);
// 使用友元函数输出宽度
printWidth( box );
return 0;
}