赋值运算符

赋值运算符

除了拷贝赋值和移动赋值,类还可以定义其他赋值运算符以使用别的类型作为右侧运算对象。

赋值运算符必须定义为成员函数。

class StrVec
{
public:
	StrVec &operator=(std::initializer_list<std::string>);
};

StrVec & StrVec::operator=(std::initializer_list<std::string> il)
{
	auto data = alloc_n_copy(il.begin(),il.end());
	free();
	elements = data.first;
	first_free = cap = data.second;
	return *this;
}

复合赋值运算符

复合赋值运算符不必一定是类的成员函数,但是最好把包含复合赋值在内的所有赋值运算都定义在类的内部,为了与内置类型的复合赋值保持一致,类中的复合赋值运算符也要返回其左侧运算对象的引用。

Sales_data &Sales_data::operator += (const Sales_data &rhs)
{
	units_soled += rhs.units_soled;
	revenue += rhs.revenue;
	return *this;
}
原文地址:https://www.cnblogs.com/xiaojianliu/p/12496458.html