-2

对于以下示例:

#include <iostream>

using namespace std;

class Obj {
    public:
        Obj& operator=(const Obj& o) {
            cout << "Copy assignment operator called" << endl;
            return *this;
        }
};

Obj o;

int update(Obj& o) {
    o = ::o;
}

int main() {
    Obj o2;
    update(o2);
}

我得到结果:

Copy assignment operator called

为什么在将对象分配给引用时使用复制分配?为什么引用没有更新为指向分配的对象?这是惯例问题还是背后有原因?

4

1 回答 1

1

Assigning to a reference assigns to the object the reference refers to, not the reference itself. Thus, your update function is equivalent to:

o2 = ::o;
于 2019-04-19T18:59:21.397 回答