分配给引用时,为什么会出现此错误(C2582:'operator ='函数在'B'中不可用)?

问题描述:

在此模板函数中,我尝试从boost ptr_map中检索at元素.为了清楚起见,我省略了错误处理代码.

In this template function, I am trying to retrieve at element from a boost ptr_map. I have omitted error handling code for clarity.

template <typename K, class T>
class A
{
public:
    void TryGet(const K &key, T &o) { o = mObjects.at(key); }
private:
    boost::ptr_map<K, T> mObjects;
};

typedef A<std::string, B> myClass;

我得到编译器错误C2582:'B'中没有'operator ='函数.为什么将mObjects.at()的返回值分配给引用,需要访问实例化类的赋值运算符?返回此值的正确方法是什么?

I get the compiler error C2582: 'operator =' function is unavailable in 'B'. Why does the assignment of the return value of mObjects.at() to a reference need access to an assignment operator of the instantiated class? What is the correct way to return this value?

为什么将mObjects.at()的返回值分配给引用,需要访问实例化类的赋值运算符?

Why does the assignment of the return value of mObjects.at() to a reference need access to an assignment operator of the instantiated class?

分配给引用时,就是分配给引用所引用的对象.

When you are assigning to a reference, you are assigning to the object that the reference references.

int i = 0;
int& iRef = i;   // There is no assignment, just initializing the reference.
iRef = 10;       // Same as i = 10

更新,以回应OP的评论

您所看到的等同于:

int j = 10;
int& jRef = j;
iRef = jRef;     // Same as i = j