繁体   English   中英

在 C++ 中重载运算符的引用

[英]reference at overloading operator in c++

我是 C++ 新手,最近我在尝试理解重载函数。 我对运算符重载中的引用有疑问。 我知道 CBoys& 是对类 CBoys 的引用,但我没有看到以下 5 个运算符 = 重载的区别。

class CBoys{
//operator=(const CBoys&);
//operator=(const CBoys);
}
// CBoys& operator=(const CBoys&);
// CBoys operator=(const CBoys&);
// CBoys& operator=(const CBoys);

谢谢帮助

那么,对于初学者来说,

operator = (const CBoys&);

operator = (const CBoys);

无效。 唯一一次省略返回类型(运算符就像函数)是在重载转换运算符时。 例如

operator bool();

当在您的类型中定义时,将创建一个将您的类型隐式转换为 bool 的方法。

至于其余的,它们都根据它们的返回类型和它们接受的参数而有所不同。第一个, CBoys& operator=(const CBoys&); 接受对常量 CBoys 的引用并返回对 CBoys 的引用。 第二个按值返回 CBoys。 第三个虽然很好,但会复制您传递给它的 CBoys(右侧的对象)。

长话短说,运算符重载的参数的常量性和引用性意味着它们在常规函数声明中所做的相同的事情。

实现复制赋值运算符重载通常非常简单:

class CBoys {
    // stuff
public:
    CBoys& operator = (const CBoys& rhs) {
        CBoys temp(rhs); // make a copy.
        using std::swap;
        swap(*this, temp); // and swap the old *this with the new object.
        return *this; // return the object by-reference.
    }
};

这允许我们以一种直接的方式使用赋值运算符而不会感到意外,因为它的行为类似于内置类型的赋值运算符。 有关复制赋值运算符的更多信息,请参见此处: http : //en.cppreference.com/w/cpp/language/as_operator

我希望这有助于您的理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM