&运算符在重载方面意味着什么

0 c++ stl overloading class vector

我正在读一本C++书.该程序试图制作一个对象矢量.这是我不明白的部分

class X {
public:
    X();
    X(int m) {
        temp = x;
    }

    int temp;


    X &operator =(int z) {
        temp = z;
        return *this;
    }

private :
    //            Some functions here
}
Run Code Online (Sandbox Code Playgroud)

上面的线是什么意思?这是某种超载吗?那怎么样?

Mar*_*som 6

我假设你有一个拼写错误,该行实际上是:

X &operator =(int z) {
Run Code Online (Sandbox Code Playgroud)

&装置,该返回类型是参考; 你应该把它读作operator =一个返回类型的函数X &.

  • @Mooing:无论如何它被称为"运算符重载",因为你为类类型重载了`x = y`的基本含义. (2认同)

Mik*_*our 5

如果稍微改变间距,意思可能会更清楚:

X& operator= (int z)
Run Code Online (Sandbox Code Playgroud)

这是赋值运算符 的重载operator=,它接受一个int参数,并返回对 的引用class X

您可以使用它为对象分配整数值:

X x;
x = 42; // calls the overloaded operator
Run Code Online (Sandbox Code Playgroud)

返回值允许您链接分配:

X x1,x2;
x1 = x2 = 42;   // equivalent to `x2 = 42; x1 = x2;`
(x1 = x2) = 42; // equivalent to `x1 = x2; x1 = 42;`
Run Code Online (Sandbox Code Playgroud)