同名函数
代码示例:
class Student {
public:
void eat() {
cout << "Student::eat()" << endl;
}
};
class Worker {
public:
void eat() {
cout << "Worker::eat()" << endl;
}
};
class Undergraduate : public Student, public Worker {
public:
void eat() {
cout << "Undergraduate::eat()" << endl;
}
};
如何调用父类的同名函数
int main() {
Undergraduate ug;
ug.eat(); // Undergraduate::eat()
ug.Worker::eat(); // Worker::eat()
ug.Student::eat(); // Student::eat()
ug.Undergraduate::eat();// Undergraduate::eat()
getchar();
return 0;
}
同名变量
class Student {
public:
int m_age;
};
class Worker {
public:
int m_age;
};
class Undergraduate : public Student, public Worker {
public:
int m_age;
};
int main() {
Undergraduate ug;
ug.m_age = 10;
ug.Student::m_age = 20;
ug.Worker::m_age = 30;
ug.Undergraduate::m_age = 40;
cout << ug.Undergraduate::m_age << endl; // 40
cout << ug.Student::m_age << endl; // 20
cout << ug.Worker::m_age << endl; // 30
cout << sizeof(Undergraduate) << endl; // 12
getchar();
return 0;
}
同名函数和同名变量都是针对父类与子类