c++ - C++中重载运算符的引用

标签 c++ reference overloading

我是 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

希望这有助于您的理解。

关于c++ - C++中重载运算符的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22945221/

相关文章:

c++ - 带有功能支持的 Postfix 的中缀

c# - 静态方法如何调用虚方法?

C++ 重载输出运算符

c++ - 将子类列表转换为父类(super class)列表

c++ - CMake 错误查找 Boost header

c++ - 错误 : undefined reference to 'player()'

visual-studio-2008 - 使用 Visual Studio 管理源代码管理中的引用

c++ - 将对类的引用声明为类成员

c++ - 具有 32 位/64 位整数重载的模板函数

c++ - 调用和打印函数,它们在C++中返回数组