代码片段----重载操作符

#include <time.h>
#include <opencv2\opencv.hpp>
#include <iostream>
#include <memory>


class TEST
{
public:
	TEST() = default;
	TEST(std::string s) : str(s)
	{}

	~TEST() = default;

	std::string& operator + (std::string s)
	{
		this->str += "0000" + s;
		return str;
	}

	std::string& operator ++ () // 对应 ++i
	{
		this->str += "78";
		return str;
	}

	std::string& operator ++ (int) // 对应 i++
	{
		this->str += "78";
		return str;
	}

	std::string getData()
	{
		return this->str;
	}

private:
	std::string str;
};

// #1 引用函数的参数,当然该参数也是一个引用
// #2 千万不要返回局部对象的引用
std::ostream& operator << (std::ostream& out, TEST a) // 可以调用 cout<< 输出
{
	out << a.getData();
	return out;
}



int main()
{
	TEST a("good");

	std::cout << (a++) << std::endl;


    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014488388/article/details/78725549