The default assignment operator in the inner class with reference elements

I had a problem that I don’t understand, and I was hoping that someone here could give some insight. The simplified code is as follows (the source code is an implementation of a user queue / iterator queue):

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 compiles the following error when compiling:

 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 

I can get around this using two separate C variables, since they must be independent C objects, but this only hides the problem (I still don't understand why I cannot do this).

I think the reason is that the link cannot be copied, but I do not understand why. Do I need to provide my own assignment operator and copy constructor?

+7
c ++ assignment-operator reference
source share
4 answers

This problem has nothing to do with inner classes. In C ++, you simply cannot (re) assign links - you need to initialize them when they are defined.

A simpler example:

 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; } 
+13
source share

The link cannot be changed after receiving its initial value. This means that it is not possible to write an assignment statement that changes the value of a reference element. If you need to do this, use a pointer instead of a link.

+6
source share

Actually, there is a solution to this. You can implement the = operator in terms of building a copy , and it will work :) This is a very capable method for such cases. Assuming you want to maintain an appointment.

+3
source share

C ++ does not have "inner classes", just nested class declarations. "Inner classes" are Java-ism, which I think are not found in other major languages. In Java, inner classes are special because they contain an implicit, immutable reference to an object of the containing type. Reaching equivalent C ++ nested declarations in Java requires the use of static inner classes; static inner classes do not reference an object of type declaration.

0
source share

All Articles