Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The reason for the compiler error is a circular dependency. Each of your operator=() functions require knowledge of the operator=() function inside the other class, so no matter which order you define your classes in, there will always be an error.</p> <p>Here is one way to sort it out. It isn't very elegant, but it will do what you want:</p> <pre><code>class A; class B; A &amp; set_equal(A &amp; a, const B &amp; b); B &amp; set_equal(B &amp; a, const A &amp; a); class A { private: int x; public: A &amp; operator=(const B &amp; b) { return set_equal(*this, b); } friend B &amp; set_equal(B &amp; b, const A &amp; a); friend A &amp; set_equal(A &amp; a, const B &amp; b); }; class B { private: int y; public: B &amp; operator=(const A &amp; a) { return set_equal(*this, a); } friend A &amp; set_equal(A &amp; a, const B &amp; b); friend B &amp; set_equal(B &amp; b, const A &amp; a); }; A &amp; set_equal(A &amp; a, const B &amp; b) { a.x = b.y; return a; } B &amp; set_equal(B &amp; b, const A &amp; a) { b.y = a.x; return b; } </code></pre> <p>You may also be able to solve this problem with inheritance.</p> <p><b>edit:</b> here is an example using inheritance. This will work if the copying procedure only needs access to some common data shared by both A and B, which would seem likely if the = operator is to have any meaning at all.</p> <pre><code>class A; class B; class common { protected: int x; void copyFrom(const common &amp; c) { x = c.x; } }; class A : public common { public: A &amp; operator=(const common &amp; c) { copyFrom(c); return *this; } }; class B : public common { public: B &amp; operator=(const common &amp; c) { copyFrom(c); return *this; } }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload