l***e 发帖数: 480 | 1 写了个类,也加了operator<<
可等输出时,c<
编译报错:
啥问题? |
S**I 发帖数: 15689 | 2 把<<定义成member function了?
【在 l***e 的大作中提到】 : 写了个类,也加了operator<< : 可等输出时,c<: 编译报错: : 啥问题?
|
l***e 发帖数: 480 | 3 class aaa {
public:
string str;
int i;
ostream & operator<< (ostream & stream) {
stream << str << " " <
return stream;
}
}
OK? |
S*********g 发帖数: 5298 | 4 no.
put << outside of your class definition.
【在 l***e 的大作中提到】 : class aaa { : public: : string str; : int i; : ostream & operator<< (ostream & stream) { : stream << str << " " <: return stream; : } : } : OK?
|
l***e 发帖数: 480 | |
S*********g 发帖数: 5298 | 6 Yes you can. But you need to use it as member function.
【在 l***e 的大作中提到】 : <<好像可以定义在类里吧。
|
S**I 发帖数: 15689 | 7 you mean friend nonmember function?
【在 S*********g 的大作中提到】 : Yes you can. But you need to use it as member function.
|
S*********g 发帖数: 5298 | 8 If operator<< is defined as class member function,
one cannot call it as std::cout << aa;
aa.operator<<(cout) will be the right way to call it.
【在 S**I 的大作中提到】 : you mean friend nonmember function?
|
l***e 发帖数: 480 | 9 通过了,执行正确。
如何定义在类外?
class aaa {
public:
string str;
int i;
}
edge::ostream & operator<< (ostream & stream) {
stream << str << " " <
return stream;
}
【在 S*********g 的大作中提到】 : If operator<< is defined as class member function, : one cannot call it as std::cout << aa; : aa.operator<<(cout) will be the right way to call it.
|
S*********g 发帖数: 5298 | 10 As someone else have said, you usually want to define
it as friend non-member function since you will probably
need to access private/protected informations of class aaa in this function.
class aaa{
private:
string str;
int i;
friend ostream& operator<<(ostream& os, const aaa& a)
{
return os << a.str << " "<< a.i << std::endl;
}
};
【在 l***e 的大作中提到】 : 通过了,执行正确。 : 如何定义在类外? : class aaa { : public: : string str; : int i; : } : edge::ostream & operator<< (ostream & stream) { : stream << str << " " <: return stream;
|
l***e 发帖数: 480 | |