理解运算符重载 3
#include "stdafx.h"
#include <iostream>
#include <string>
//
//函数重载
//
namespace operator_test
{
//
//先定义一个类
//
class CObject
{
friend std::ostream& operator<<(std::ostream& out, CObject& object);
public:
CObject(int a) : m_a(a)
{
}
int Get()
{
return m_a;
}
CObject& operator+(CObject& obj2)
{
this->m_a += obj2.Get();
return *this;
}
private:
int m_a;
};
std::ostream& operator<<(std::ostream& out, CObject& object)
{
out << object.m_a;
return out;
}
}
void test_operator_test()
{
operator_test::CObject obj1(10);
operator_test::CObject obj2(20);
//
//返回值,把int operator+(CObject& obj2)改成 CObject& operator+(CObject& obj2)
//
std::cout << obj1 + obj2 << std::endl;
//std::cout << obj1 + obj2返回一个std::ostream&,接着往这个返回的ostream写入std::endl;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步