Does the assignment operator work with various types of objects?

class A { public: void operator=(const B &in); private: int a; }; class B { private: int c; } 

excuse me. An error has occurred. is the assignment operator valid? or is there a way to achieve this? [There is no connection between classes A and B.]

 void A::operator=(const B& in) { a = in.c; } 

Thank you very much.

+4
source share
4 answers

Yes you can do it.

 #include <iostream> using namespace std; class B { public: B() : y(1) {} int getY() const { return y; } private: int y; }; class A { public: A() : x(0) {} void operator=(const B &in) { x = in.getY(); } void display() { cout << x << endl; } private: int x; }; int main() { A a; B b; a = b; a.display(); } 
+8
source

Both assignment operators and parameter constructors can have parameters of any type and use the values โ€‹โ€‹of these parameters in any way that they want to initialize the object.

+1
source

This is not an answer, but remember that a typical idiom for an assignment operator is to return a reference to the type of the object (rather than void) and return (* this) at the end. So you can bind the assignment, as in = b = c:

 A& operator=(const A& other) { // manage any deep copy issues here return *this; } 
+1
source
Others have talked about this, but I actually state it. Yes, you can use different types, but note that if you are not using a friend, your class cannot access the private members of the class that are passed along with the operator.

A value will not be able to access B :: c because it is closed.

0
source

All Articles