栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

c++,运算符重载,左移运算符&自增运算符。

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++,运算符重载,左移运算符&自增运算符。

假设有类A,它的私有成员是一个整型变量a_

A a;

我们想要把它的私有成员直接用 cout<

我们把<<运算符重载为全局函数,在类A中设为友元,即可直接用cout输出。

关于自增运算符,要实现a++,++a;需要重载前置自增,后置自增运算符。

#include
using namespace std;
class A
{
	friend ostream& operator<<(ostream& cout, A& A_);
private:
	int a_num;
public:
	A() = default; //        自动生成无参构造函数 
	A(int x) :a_num(x) {} // 构造函数 
	A& operator++() //     重载前置自增运算符 
	{
		a_num++;
		return *this;
	}
};
ostream& operator<<(ostream& cout, A& A_) // 重载左移运算符 
{
	cout << A_.a_num;
	return cout;
}
int main()
{
	A a1(5);
	cout << "before:" << a1 << endl;
	cout << "after:" << ++a1 << endl;
	cout << "final:" << a1 << endl;


	system("pause");
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1028126.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号