Apr
29
Overload operator <<
felix写的一个简单例子:
#include <iostream>
using namespace std;
class testclass{
public:
int a, b;
testclass(int a1, int b1){
a = a1, b = b1;
}
friend ostream & operator <<(ostream & os, testclass a1){
cout << "a = " << a1.a << ", b = " << a1.b << endl;
return os;
}
friend ostream & operator <<(ostream & os, testclass *a1){
cout << "a = " << a1->a << ", b = " << a1->b << endl;
return os;
}
};//end of testclass
int main(){
testclass *a1 = new testclass(1, 2);
cout << a1;
cout << *a1;
getchar();
return 0;
}
下面是更详细的重载各个流操作符的例子,原出处是Thinking In C++
copy 自 http://www.cndev.org/forum/msg.aspx?pid=233806
felix写的一个简单例子:
#include <iostream>
using namespace std;
class testclass{
public:
int a, b;
testclass(int a1, int b1){
a = a1, b = b1;
}
friend ostream & operator <<(ostream & os, testclass a1){
cout << "a = " << a1.a << ", b = " << a1.b << endl;
return os;
}
friend ostream & operator <<(ostream & os, testclass *a1){
cout << "a = " << a1->a << ", b = " << a1->b << endl;
return os;
}
};//end of testclass
int main(){
testclass *a1 = new testclass(1, 2);
cout << a1;
cout << *a1;
getchar();
return 0;
}
下面是更详细的重载各个流操作符的例子,原出处是Thinking In C++
copy 自 http://www.cndev.org/forum/msg.aspx?pid=233806