概念:重载和重写
函数三要素: 函数名,返回类型,参数列表
重载: 函数名相同,参数列表不同
重写: 三要素相同
基类和子类之间的重载和重写
- 子类可以重写父类中的虚函数,重写函数与被重写函数三要素相同,可以使用override关键字标识;
- 子类无法重载父类中的虚函数,重载发生在同一个类中;
TEST
class Base {
public:
virtual void PrintSomething() = 0;
};
class CA : public Base {
public:
void PrintSomething() override {
printf("hello CA.\n");
}
};
class CB : public Base {
public:
void PrintSomething(int a) {
printf("print %d.\n", a);
}
};
int main() {
Base *A = new CA();
Base *B = new CB();
CB cb;
int n = 2;
A->PrintSomething();
B->PrintSomething(n);
cb.PrintSomething(n);
system("pause");
return 0;
}
问题1:子类必须重写父类中的虚函数,否则无法实例化;

问题2:子类无法重载父类的虚函数;

修改后可成功编译并运行得到结果
class Base {
public:
virtual void PrintSomething() = 0;
};
class CA : public Base {
public:
void PrintSomething() override {
printf("hello CA.\n");
}
};
class CB : public Base {
public:
void PrintSomething(int a) {
printf("hello %d.\n", a);
}
void PrintSomething() override {
printf("override functione.\n");
}
};
int main() {
Base *A = new CA();
Base *B = new CB();
CB cb;
int n = 2;
A->PrintSomething();
B->PrintSomething();
cb.PrintSomething(n);
system("pause");
return 0;
}

本文介绍了C++中基类与子类之间的重载和重写概念。重载发生在同一类中,通过函数名相同但参数列表不同来实现。重写则是在子类中,当函数名、返回类型和参数列表都与父类的虚函数相同时,可以使用`override`关键字标识。子类必须重写父类的虚函数才能实例化,并且不能重载这些虚函数。

1379

被折叠的 条评论
为什么被折叠?



