// C++ 框架代码示例:一个简单的类和继承结构
#include <iostream>
#include <string>
// 基类
class Base {
public:
// 构造函数
Base(const std::string& name) : name(name) {
std::cout << "Base constructor called for " << name << std::endl;
}
// 虚析构函数,确保派生类的析构函数能被正确调用
virtual ~Base() {
std::cout << "Base destructor called for " << name << std::endl;
}
// 纯虚函数,必须在派生类中实现
virtual void display() const = 0;
protected:
std::string name;
};
// 派生类
class Derived : public Base {
public:
// 构造函数
Derived(const std::string& name, int value) : Base(name), value(value) {
std::cout << "Derived constructor called for " << name << " with value " << value << std::endl;
}
// 析构函数
~Derived() override {
std::cout << "Derived destructor called for " << name << std::endl;
}
// 实现基类的纯虚函数
void display() const override {
std::cout << "Displaying from Derived: " << name << ", value = " << value << std::endl;
}
private:
int value;
};
int main() {
// 创建派生类对象
Derived d("derived_object", 42);
// 调用派生类的 display 函数
d.display();
return 0;
}
基类 Base:
display(),这意味着任何派生类都必须实现这个函数。派生类 Derived:
Base 类。display()。value 和相应的构造函数、析构函数。主函数 main:
Derived 类的对象,并调用了其 display() 方法。这个示例展示了如何使用 C++ 的类和继承机制来构建一个简单的框架代码。通过定义基类和派生类,可以实现代码的复用和扩展。
上一篇:c++格式化字符串
下一篇:c++如何判断素数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站