本文主要介绍操作符与输入输出符的重载相关问题
operator与操作符
operator是操作符重载关键字,和public、const同一地位。
主要重载“+”、“-”、“++”等操作符
使用格式为operator直接连接要重载的操作符,函数在类内实现,代码逻辑清晰直观
class Box
{
public:
Box(int da){data = da;}
Box operator+(const Box& b)
{
Box c(0);
c.data = data + b.data;
return c;
}
int getData(){ return data;}
private:
int data;
};
int main( )
{
Box a(10);
Box b(15);
Box c(0);
c = a + b;
cout << c.getData();
return 0;
}
运行结果:25
流的输出符“<<”与ostream(“>>”与istream同理)
流的输出符重载的实现有两种形式,需要注意到的是,“<<”的左边是cout,且不能更改,在调用时
主体为ostream类,即"ostream.XXX"的形式。而外部类是访问不到重载输出符的类的私有变量的。
这也是为什么第一种实现形式为friend友元操作符(通过friend声明可以使被修饰的类访问本类的私有变量),缺点是破坏了程序的封装性,优点是实现简洁,只需一个声明。
第二种形式为“曲线救国”,即在类内使用“ostream&”作为参数,在类内声明的函数中编写输出符重载逻辑,在类外的普通函数中通过类内函数暴露的私有变量重载输出符,《数据结构C++语言实现》的版本中使用的即为这种形式,保护了程序的封装性。
第一种:使用友元函数在类内实现
class Box
{
public:
Box(int da){data = da;}
friend ostream& operator<<(ostream& out, const Box& x);
private:
int data;
};
ostream& operator<<(ostream& out, const Box& x)
{
out << "just yanzhi flavor left ";
out << x.data << endl;
return out;
}
int main( )
{
Box box(10);
cout << box;
return 0;
}
//运行结果:Just yanzhi flavor left 10
第二种:在类内声明函数A()并传入ostream&,并在类外的重载函数中调用A()
class Box
{
public:
Box(int da){data = da;}
void output(ostream& out) const;
private:
int data;
};
void Box :: output(ostream& out) const
{
out << "Just yanzhi flavor left ";
out << data << endl;
}
ostream& operator<<(ostream& out, const Box& x)
{
x.output(out);
return out;
}
int main( )
{
Box box(10);
cout << box;
return 0;
}
运行结果
参考:https://blog.csdn.net/qq_35817700/article/details/70657713