您的位置:首页 > 编程语言 > C语言/C++

C++之流运算符重载

2016-06-04 12:07 330 查看
之前说到流的时候提到过,cin和cout是一种流对象,对于这样的一句代码:

cout << a << b << endl;


实际的步骤是这样的,a先流到cout里面,然后b再流到cout的里面,最后endl流到cout里面,可以看看出来“<<”是一个双目操作符,那我们是不是也可以用友元重载和成员函数重载来分别实现呢?

这里要说一下,”<<”和“>>”都只能使用友元重载实现,不能用成员函数重载,稍微解释一下为什么:

“<<”和”>>”的左边分别是cout和cin,如果想用成员函数重载实现,那必须要修改标准库ostream和istream,到这两个库中去成员函数重载,显然这是不可以的,那就只能用友元重载实现了。还是举个例子来实现:

class Complex{
private:
float _x;
float _y;
public:
Complex(float x = 0, float y = 0):_x(x), _y(y){}
friend ostream& operator <<(ostream& os, const Complex& a){
os << "( " << a._x << "," << a._y << " )";
return os;
}
friend istream& operator >>(istream& is, Complex& a){
is >> a._x;
is >> a._y;
return is;
}
};

int main()
{
Complex c;
cin >> c;
cout << c << endl;
return 0;
}


这里注意两点,一个是友元重载返回值类型,一个是参数,就不多解释了,与前面的双目运算符重载大同小异。

这里要多说一个例子,对于自己编写的string类型的流运算符的重载:

class MyString
{
public:
MyString(char *str = "");
~MyString();
friend ostream& operator <<(ostream& os, const MyString &s);
friend istream& operator >>(istream& is, MyString  &s);
private:
char *_str;
};

MyString::MyString(char *c)
{
int len = strlen(c);
_str = new char[len + 1];
strcpy(_str, c);
}

MyString::~MyString() {
delete[]_str;
}

ostream& operator <<(ostream& os, const MyString &s) {
os << s._str;
return os;
}

istream& operator >>(istream& is, MyString &s) {
is >> s._str;
return is;
}


流输出运算符重载没什么好说的,重点看一下流输入运算符,首先要知道直接对一个char 类型进行直接输入是有危险的, 因为不知道要输入多少个字符,那系统就不知道开辟多少个空间,有可能空间不够,有可能空间浪费,这都是不可取的,那就用一个固定空间大小的char buf[BUFSIZ];来代替char 的输入,代码修改一下:

istream& operator >>(istream& is, MyString &s) {
delete[]s._str;
char buf[BUFSIZ];
is >> buf;
int len = strlen(buf);
s._str = new char[len + 1];
strcpy(s._str, buf);
return is;
}


这样就保证了一种安全性,这是字符串流输入重载需要注意的一点。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: