左移和右移运算符的重载问题(里面的绝对盲点)在做了一遍,还是出错了
#include <iostream>
//实现左移和右移的重载。
using namespace std;
class A
{
public:
friend ostream operator<<(ostream &t1,A &a0);
public:
A(int i)
{
this->a=i;
}
public:
int a;
protected:
};
ostream operator<<(ostream &t1,A &a0)
{
t1<<a0.a<<endl;
return t1;
}
int main()
{
A a1(10);
cout<<a1;
system("pause");
return 0;
}
上面这种是错的,因为定义了类ostream的对象,其他人员是不能改变iostream的任何变量和对象的,所以这里要加一个引用才对呢
#include <iostream>
//实现左移和右移的重载。
using namespace std;
class A
{
public:
friend ostream &operator<<(ostream &t1,A &a0);
public:
A(int i)
{
this->a=i;
}
public:
int a;
protected:
};
ostream &operator<<(ostream &t1,A &a0)
{
t1<<a0.a<<endl;
return t1;
}
int main()
{
A a1(10);
cout<<a1;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class sten_fri
{
public:
sten_fri(int a)
{
this->a = a;
}
friend ostream &operator <<(ostream &out, sten_fri sf);
protected:
private:
int a;
};
ostream &operator <<(ostream &out, sten_fri sf)
{
out << sf.a << endl;
return out;
}
int main()
{
sten_fri a1(5);
cout << a1;//这里的友元函数中ostream out中间必须加引用,要不然是错误的。
system("pause");
return 0;
}

浙公网安备 33010602011771号