Я хотел бы иметь возможность копировать производный или базовый объект в производный объект, и я хотел бы, чтобы правильный оператор выбирался полиморфно в зависимости от типа копируемого объекта.
Этокод не работает, я бы хотел b1 = (A&)b2;
использовать B & operator= (B const &other)
, потому что b2
это B
, но он использует B & operator= (A const &other)
:
#include<iostream>
using namespace std;
class A {
public:
A & operator= (A const &other) {
// Here copy A members...
cout<<"A to A"<<endl;
return *this;
}
};
class B: public A {
public:
B & operator= (A const &other) {
A::operator=(other); // Copy A members.
cout<<"A to B"<<endl;
return *this;
}
B & operator= (B const &other) {
A::operator=(other); // Copy A members.
// Here copy B members...
cout<<"B to B"<<endl;
return *this;
}
};
int main()
{
B b1, b2;
A a2;
b1 = b2;
cout<<endl;
b1 = (A&)b2;
cout<<endl;
b1 = a2;
cout<<endl;
return 0;
}
Я думаю, мне нужно что-то сделать virtual
но я не могу найти как.