Cout的扩展续

Cout的扩展续
        本文简要介绍一下如何进行类的输入输出扩展,其实这个需求并不难,我们只需要简单得在类的内部重载“<<”操作符为友元函数而已。见下面示例程序:




#include<iostream>
#include<iterator>

using namespace std;

class car{

public:
	car(){}
	car(int v,int spe,int spa):value(v),speed(spe),space(spa){}
	car(car& c){*this = c;}
	~car(){}
	
	car& operator=(car &c);
	friend istream& operator>>(istream &os,car& c);//注意此处不能const
	friend ostream& operator<<(ostream &os,const car& c);

	void GetAddr(){cout<<&value<<" "<<&speed<<" "<<&space<<endl;}


private:
	int value;
	int speed;
	int space;
};

car& car::operator=(car &c)
{
	this->value = c.value;
	this->speed = c.speed;
	this->space = c.space;
}

istream& operator>>(istream &os,car& c)
{
	cout<<"Pls input:"<<endl;
	cout<<"value:";
	os>>c.value;
	cout<<"speed:";
	os>>c.speed;
	cout<<"space:";
	os>>c.space;
}

ostream& operator<<(ostream &os,const car& c)
{
	os<<"value:"<<c.value<<endl;
	os<<"speed:"<<c.speed<<endl;
	os<<"space:"<<c.space<<endl;
}


int main()
{
	car BMW(100,200,6);
	car BMW2(BMW);
	cout<<"*****BMW*****:"<<endl<<BMW;
	cout<<"*****BMW2*****:"<<endl<<BMW2;
	BMW.GetAddr();
	
	car qq;
	cin>>qq;
	cout<<"*****qq*****"<<endl<<qq;
}
*****BMW*****:
value:100
speed:200
space:6
*****BMW2*****:
value:100
speed:200
space:6
0xbfcceb74 0xbfcceb78 0xbfcceb7c
Pls input:
value:30
speed:100
space:4
*****qq*****
value:30
speed:100
space:4
        从上面代码可以看出,实现类的输入输出其实并不困难,这就是C++ 的强大之处啊。从输出地址我们可以看到,类内部的成员变量是顺序存储于堆栈之中的,我们由此萌生出一个函数输出所有自定义类的方法(其他标准类不能保证其属于一个命名空间,那样会找不到重载函数)。
        额,不同元素步进不同,不知道怎么解决,先搁着吧!



你可能感兴趣的:(C++,重载,STL,输入输出,cout)