内部类中的引用成员的默认赋值运算符 [英] Default assignment operator in inner class with reference members
问题描述
我遇到了一个我不明白的问题,我希望这里的人能提供一些见解。简化代码如下(原始代码是自定义队列/队列迭代器实现):
I've run into an issue I don't understand and I was hoping someone here might provide some insight. The simplified code is as follows (original code was a custom queue/queue-iterator implementation):
class B
{
public:
B() {};
class C
{
public:
int get();
C(B&b) : b(b){};
private:
B& b;
};
public:
C get_c() { return C(*this); }
};
int main()
{
B b;
B::C c = b.get_c();
c = b.get_c();
return EXIT_SUCCESS;
}
编译时会出现以下错误:
This, when compiled, gives me the following error:
foo.cpp: In member function 'B::C& B::C::operator=(const B::C&)':
foo.cpp:46: error: non-static reference member 'B& B::C::b', can't use default assignment operator
foo.cpp: In function 'int main()':
foo.cpp:63: note: synthesized method 'B::C& B::C::operator=(const B::C&)' first required here
可以通过使用两个单独的C变量,因为它们应该是独立的C对象,但这只是隐藏的问题(我仍然不明白为什么我不能这样做)。
I can go around this by using two separate C variables, as they are supposed to be independent 'C' objects, but this only hides the problem (I still don't understand why I can't do this).
我认为原因是引用不能被复制,但我不明白为什么。我需要提供自己的赋值运算符和复制构造函数吗?
I think the reason is that the reference cannot be copied, but I don't understand why. Do I need to provide my own assignment operator and copy constructor?
推荐答案
这个问题与内部类无关。在C ++中,你不能(重新)分配引用 - 它们需要在定义时初始化。
This problem has nothing to do with inner classes. In C++ you just can't (re)assign references - they need to be initialised when defined.
一个更简单的例子是:
class B
{
public:
B(int& i) : ir(i) {};
int& ir;
};
int main()
{
int i;
B b(i); // Constructor - OK
int j;
B bb = B(j); // Copy constructor - OK
bb = b; // Assignment - Error
return 0;
}
这篇关于内部类中的引用成员的默认赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!