赋值运算符

时间:2020-03-15 11:19:24   收藏:0   阅读:45

赋值运算符

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

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

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;
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!