Friday, February 11, 2022

[c++] Overloading assignments (C++ only)

struct X {

  int data;

  X& operator=(X& a) { return a; }

  X& operator=(int a) {

    data = a;

    return *this;

  }

};


int main() {

  X x1, x2;

  x1 = x2;      // call x1.operator=(x2)

  x1 = 5;       // call x1.operator=(5)

}

==============================================================

#include <iostream>

using namespace std;


struct A {

  A& operator=(char) {

    cout << "A& A::operator=(char)" << endl;

    return *this;

  }

  virtual A& operator=(const A&) {

    cout << "A& A::operator=(const A&)" << endl;

    return *this;

  }

};


struct B : A {

    B& operator=(char) {

      cout << "B& B::operator=(char)" << endl;

      return *this;

    }

    virtual B& operator=(const A&) {

      cout << "B& B::operator=(const A&)" << endl;

      return *this;

    }

};


struct C : B { };


int main() {

  B b1;

  B b2;

  A* ap1 = &b1;

  A* ap2 = &b1;

  *ap1 = 'z';

  *ap2 = b2;


  C c1;

//  c1 = 'z';

}

A& A::operator=(char)

B& B::operator=(const A&)


The assignment *ap1 = 'z' calls A& A::operator=(char). Because this operator has not been declared virtual, the compiler chooses the function based on the type of the pointer ap1.

The assignment *ap2 = b2 calls B& B::operator=(const &A). Because this operator has been declared virtual, the compiler chooses the function based on the type of the object that the pointer ap1 points to. 

The compiler would not allow the assignment c1 = 'z' because the implicitly declared copy assignment operator declared in class C hides B& B::operator=(char).


No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能