当前位置: 首页 > news >正文

QT编程练习20250507

#include <stdio.h>  // 包含标准输入输出库
#include <stdlib.h> // 包含通用工具库(如malloc, free等)
#include <string>   // 包含C++ string类定义
#include <iostream> // 包含C++输入输出流库using namespace std; // 使用std命名空间,避免每次调用标准库函数时都需要加上前缀std::// 定义一个汽车结构体,用于表示汽车的基本信息
struct Car{ string color; // 颜色string brand; // 品牌string type;  // 车型int year;     // 年限// 函数指针,指向打印汽车信息的函数void (*printCarInfo)(string color,string brand,string type, int year); // 函数指针,指向车运行的函数void (*carRun)(string type); // 函数指针,执行车停止的函数void (*carStop)(string type); 
};// 定义一个汽车类,与上述结构体类似,但使用了类的方式,并且添加了一个成员函数realPrintCarInfo
class car{
public:string color; // 颜色string brand; // 品牌string type;  // 车型int year;     // 年限// 函数指针,指向打印汽车信息的函数void (*printCarInfo)(string color, string brand, string type, int year); // 函数指针,指向车运行的函数void (*carRun)(string type); // 函数指针,执行车停止的函数void (*carStop)(string type); // 成员函数,用于打印汽车信息void realPrintCarInfo();
};// 实现realPrintCarInfo成员函数,该函数以更直观的方式打印汽车信息
void car::realPrintCarInfo(){cout << "成员函数打印" << endl;string str = "车的品牌是:" + brand+ ",型号是: " + type+ ",颜色是:" + color+ ",上市年限是:" + std::to_string(year);cout << str << endl;
}// 定义一个打印宝马3系汽车信息的函数
void bwmThreePrintCarInfo(string color,string brand,string type, int year)
{printf("车的品牌是:%s, 型号是: %s, 颜色是:%s,上市年限是%d\n",brand.c_str(), type.c_str(), color.c_str(), year);
}// 定义一个打印奥迪A6汽车信息的函数
void A6PrintCarInfo(string color,string brand,string type, int year)
{printf("车的品牌是:%s,型号是: %s, 颜色是:%s, 上市年限是%d\n",brand.c_str(), type.c_str(), color.c_str(), year);
}int main()
{// 创建一个结构体变量BWMthree并初始化其属性值struct Car BWMthree;BWMthree.color = "白色";BWMthree.brand = "宝马";BWMthree.type = "3系";BWMthree.year = 2023;BWMthree.printCarInfo = bwmThreePrintCarInfo;// 调用BWMthree的printCarInfo函数打印信息BWMthree.printCarInfo(BWMthree.color, BWMthree.brand, BWMthree.type, BWMthree.year);// 动态创建一个car类的对象AodiA6,并初始化其属性值car *AodiA6 = new car();AodiA6->color = "黑色";AodiA6->brand = "奥迪";AodiA6->type = "A6";AodiA6->year = 2008;AodiA6->printCarInfo = A6PrintCarInfo;// 调用AodiA6的printCarInfo函数打印信息AodiA6->printCarInfo(AodiA6->color,AodiA6->brand,AodiA6->type,AodiA6->year);// 释放动态分配的内存delete AodiA6;return 0;
}

此代码示例展示了如何通过结构体和类来描述对象(这里是以汽车为例),以及如何利用函数指针实现对不同对象类型的不同行为。同时,也演示了C++中成员函数的定义与使用方法。

相关文章:

  • 【C++】C++中this指针的介绍及使用
  • k8s部署OpenELB
  • RT Thread Studio创建软件和硬件RTC工程
  • ROBOVERSE:面向可扩展和可泛化机器人学习的统一平台、数据集和基准
  • SQL 子查询
  • 如何设置飞书多维表格,可以在扣子平台上使用
  • 《硬件视界》专栏介绍(持续更新ing)
  • Selenium Web自动化测试学习笔记(一)
  • C++命名空间、内联与捕获
  • vue3父组件调用子组件方法
  • React Native主题切换、字号调整:不用styled-components也能玩出花
  • daplink开发_一次开发DAPLink的详细开发流程及调试步骤
  • Nginx性能调优与深度监控
  • 在IDEA中编写Spark程序并运行
  • 2025.05.07-华为机考第三题300分
  • C++初阶-string类4
  • DeepSeek智能时空数据分析(九):NL2SQL绘制河流名字-如何给轨迹添加说明文字
  • Qt 中基于 spdlog 的高效日志管理方案
  • 服务器上机用到的设备
  • 【spring】Spring、Spring MVC、Spring Boot、Spring Cloud?
  • 多省市已开展现房销售试点,去年全国现房销售面积占比超30%
  • 韩国执政党总统候选人更换方案被否决,金文洙候选人资格即刻恢复
  • 梅花奖在上海|朱洁静:穿越了人生暴风雨,舞台是最好良药
  • 上汽享道出行完成13亿元C轮融资,已启动港股IPO计划
  • 央行:中国政府债务扩张仍有可持续性
  • 复旦大学文科杰出教授裘锡圭逝世,享年90岁