输入输出运算符重载 运算符重载疑难知识点总结:点击打开链接

运算符重载疑难知识点总结:点击打开链接

输入输出不能被重载为成员函数!!!

1.
从运算符角度来看,输出通过输出运算符“ <<” 来完成的,输出运算符“ <<” 也称 插入 运算符,它是一个 双目 运算符,有两个操作数, 左操作数为 ostream 的一个对象(如 cout ), 右操作数 为一个 系统预定义类型 的常量或变量。例如
    cout <<"Thisis a string.\n";
完成的功能为写字符串“ This is a string. ” 到流对象 cout , cout 为标准输出流,通常为屏幕。
2.
从运算符角度来看,输入操作通过输入运算符“ >> 来完成。输入运算符“ >>” 也称 提取 运算符,它也是一个 双目 运算符,有两个操作数, 面的操作数是 istream 类的一个对象 ( cin ) 面的操作数是 系统预定义的任何数据类型的变量 。例如 :
     int x;
    
cin >>x;
此时,用户从键盘输入的数值会自动地转换为变量 x 的类型,并存入变量 x 内。 
例子:
#include<iostream.h>
class three_d {
	public:
       three_d(int a,int b,int c)
	  {   x=a; y=b; z=c; }
friend ostream& operator<<(ostream& output,three_d& ob);
 friend istream& operator>>(istream& itput,three_d& ob);
private:
int x,y,z;
	};
ostream& operator<<(ostream& output, three_d& ob)
	{   output<<ob.x<<",";
	    output<<ob.y<<",";
	    output<<ob.z<<endl;
	    return output;	} 
            istream& operator>>(istream& input, three_d& ob)
	{
	    cout<<"Enter x,y,z value:";
	    input>>ob.x;
	    input>>ob.y;
	    input>>ob.z;
	    return input;
	}
	int main()
	{  three_d obj(10,20,30); // 定义类three_d的对象obj
	    cout<<obj;                     // 输出对象obj的成员值
	    cin>>obj;     // 输入对象obj的各成员值,将原值覆盖
	    cout<<obj;             // 输出对象obj的成员值(新值)
	    return 0;
	} 


猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/80905639