23.C++函数重载和重写
约 191 字小于 1 分钟
函数重载
在同一个类中定义多个同名函数,但参数列表不同
#include <iostream>
class OverloadExample {
public:
void print(int i) {
std::cout << "Integer: " << i << std::endl;
}
void print(double d) {
std::cout << "Double: " << d << std::endl;
}
void print(std::string str) {
std::cout << "String: " << str << std::endl;
}
};
int main() {
OverloadExample obj;
obj.print(10); // 调用 print(int)
obj.print(3.14); // 调用 print(double)
obj.print("Hello"); // 调用 print(std::string)
return 0;
}
函数重写
在继承关系中,子类重新定义父类的虚函数
#include <iostream>
class Base {
public:
virtual void show() { // 父类的虚函数
std::cout << "Base class show()" << std::endl;
}
};
class Derived : public Base {
public:
void show() override { // 重写基类函数
std::cout << "Derived class show()" << std::endl;
}
};
int main() {
Base* basePtr;
Derived obj;
basePtr = &obj;
basePtr->show(); // 调用 Derived 的 show()(运行时多态)
return 0;
}