标签:out 转换运算符 插入 函数 类的成员 namespace 返回值 names size
cout 是在iostream中定义的,是ostream类的对象,ostream包含在iostream头文件里<<是左移运算符,能用在cout上是因为在iostream中对<<进行了重载ostream类的成员函数void ostream::operator<<(int n)
{
...//输出n的代码
return;
}
cout<<5即cout.operator<<(5)cout<<"this"同理void不能实现cout<<5<<"this"cout<<5<<"this"成立?cout则可以连续cout是ostream类的对象ostream & ostream::operator<<(int n)
{
...//
return *this;
}
cout<<5<<"this"本质上的函数调用形式为cout.operator<<(5).operator<<("this");class CStudent{
public:int nAge;
};
int main(){
CStudent s;
s.nAge=5;
cout<<s<<"hello";
return 0;
}
ostream & operator<<(ostream & o,const CStudent & s)
{
o<<s.nAge;
return 0;
}
cin是istream的对象cout是ostream的对象#include<iostream>
using namespace std;
class Complex
{
double real,imag;
public:
Complex (double r=0,double i=0):real(r),imag(i){};
operator double(){
return real;
}//重载强制类型转换运算符
};
int main()
{
Complex c(1.2,3.4);
cout<<(double)c<<endl;//输出1.2
double n=2+c;//等价于double n=2+c.operator double()
cout<<n;//输出3.2
}
T&operator++(); T&operator--();T1&operator++(T2); T1&operator--(T2);T operator++(int); T operator--(int);T1 operator++(T2,int); T1 operator--(T2,int);.、.*、::、?:、sizeof()、[]、->或者赋值运算符=时,运算符重载函数必须声明为类的成员函数标签:out 转换运算符 插入 函数 类的成员 namespace 返回值 names size
原文地址:https://www.cnblogs.com/2002ljy/p/12287352.html