class A {
public:
void operator=(const B &in);
private:
int a;
};
class B {
private:
int c;
}
sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.]
void A::operator=(const B& in)
{
a = in.c;
}
Thanks a lot.
From stackoverflow
-
Yes you can do so.
#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(); }Naveen : You can also make getY() as a const member function and avoid the const_cast.Dave Van den Eynde : Yes, make getY const, and don't cast constness away.Shree : True... was just lazy to go back and change it :)David RodrÃguez - dribeas : Or else make A a friend of B so that it can access private elements. -
Both assignment operator and parameterized constructors can have parameters of any type and use these parameters' values any way they want to initialize the object.
0 comments:
Post a Comment