如何用友元给类的 string私有成员输入值???
用友元函数给 string成员输入值时出错friend std::istream & operator>>(std::istream & is, const shcoo & y)
以下贴出源码
#include <iostream>
#include <string>
usingstd::string;
class shcoo
{
private:
string S_ne;
public:
shcoo(const string & x);
void xie();
void xian();
////????
friend std::istream & operator>>(std::istream & is, const shcoo & y)
{
is >> y.S_ne; //为什么执行到这里的时候出错???
return is;
}
/////????
friend std::ostream & operator<<(std::ostream & os, const shcoo & y);
};
/////--->>>
std::ostream & operator<<(std::ostream & os, const shcoo & y)
{
std::cout <<y.S_ne << std::endl;
return os;
}
void shcoo::xian()
{
std::cout << S_ne << std::endl;
}
void shcoo::xie()
{
std::cin >> S_ne;
}
shcoo::shcoo(const string & x)
{
S_ne = x;
}
把main函数加上吧 friend std::istream & operator>>(std::istream & is, const shcoo & y)
所谓输入,就是要用一些数据改变y,所以y不能是const引用,应改为
friend std::istream & operator>>(std::istream & is, shcoo & y)
页:
[1]