C ++ operator = method for const links

I am writing a class with a link to const as follows:

class B;

class foo {
  const B& b;

  foo(const B& newb): b(newb) { }

  void operator=(const foo & foo2) {
      // This does not work
      foo.b = foo2.b;
  }   
};

I am trying to define a working operator = Obviously = does not work, since I am not allowed to change the reference to the constant. Is this a way to give a link to another object?

If b is not const, C ++ will provide me with a working = operator. If I define one member as const cl, it will spit out:

warning C4512: 'foo': assignment statement cannot be generated

+3
source share
4 answers

The term you are looking for is "retraining." How in "is it possible to double-check the link?" The answer is "no, links are defined as non-rewritable." But you can use a pointer and change what it points to:

class B;

class foo {
    B* b;

    foo(const B& newb)
    {
        b = &newb;
    }

    void operator=(const foo& foo2)
    {
        b = &foo2.b;
    }   
};

, , , , (, ). , :

class B;

class foo {
    B b;

    foo(const B& newb): b(newb) { }

    void operator=(const foo& foo2)
    {
        b = foo2.b;
    }   
};

/ (, B - ), , .

+9

, . foo, foo = foo2 .

+4

, , , . , .

+3

, . .

+1
source

Source: https://habr.com/ru/post/1758066/


All Articles