Код: Выделить всё
class A {
protected:
char *name;
public:
// Constructor
A() {
name = new char[10];
strcpy(name, "Undefined");
}
// Assignment Operator
virtual A &operator=(const A &rhs) {
if (this == &rhs) {
return *this;
}
delete [] name;
name = new char[10];
strcpy(name, rhs.name);
return *this;
}
// Destructor
virtual ~A() {
delete [] name;
}
};
Код: Выделить всё
class B : public A {
int b;
// Constructor
B():A(),b(0){}
// Assignment Operator
virtual B& operator=(const B& rhs) {
if (this == &rhs) {
return *this;
}
delete [] name;
name = new char[10];
strcpy(name, rhs.name);
b = rhs.b;
return *this;
}
// Destructor
virtual ~B() {
delete [] name;
}
};
Код: Выделить всё
class C : public A {
int* c;
// Constructor
C():A() {
c = new int[10];
for(int i = 0 ; i < 10 ; i++) {
c[i] = 0;
}
}
// Assignment Operator
virtual C& operator=(const C& rhs) {
if (this == &rhs) {
return *this;
}
delete [] name;
name = new char[10];
strcpy(name, rhs.name);
delete [] c;
c = new int[10];
for (int i = 0 ; i < 10 ; i++) {
c[i] = rhs.c[i];
}
return *this;
}
// Destructor
virtual ~C() {
delete [] name;
delete [] c;
}
};
Есть ли способ вызвать оператор = или деструктор A в B или C, поэтому я не пишу назначения для всех членов снова и снова.
[*]A — это базовый класс с переменной кучи
[*]B — это класс, производный от A, с дополнительным «int b»
[*]C — это класс, производный от A, с дополнительным «char* name»
< /ул>
Подробнее здесь: https://stackoverflow.com/questions/784 ... superclass