虚函数基础写法
题目描述
补全 Base
类的定义,使得程序符合下文规定的输入输出行为。
关于输入
无
关于输出
见样例输出
核心技巧
- 不声明虚函数时,按照变量声明类型确定访问对象。
参考答案
#include <iostream>
class Base {
public:
void f() {
std::cout << "Base::f" << std::endl;
}
virtual void g() {
std::cout << "Base::g" << std::endl;
}
};
class Derived : public Base {
public:
void f() {
std::cout << "Derived::f" << std::endl;
}
void g() {
std::cout << "Derived::g" << std::endl;
}
};
int main() {
Base* ptr1 = new Base{};
ptr1->f();
ptr1->g();
delete ptr1;
Base* ptr2 = new Derived{};
ptr2->f();
ptr2->g();
delete ptr2;
auto obj3 = Derived{};
obj3.f();
obj3.g();
}