QT学习(三) C++类

一、 类的初探

C++ 中的类( class )是一种编程结构,用于创建对象。这些对象可以拥有属性(即数据成员)和行为即成员函数或方法)。类的概念是面向对象编程的核心之一,其主要目的是将数据和与数据相关的操 封装在一起。例如,如果你有一个 汽车 类,它可能包含颜色、品牌、型号等属性(数据成员),以及 启动、停止、加速等行为(成员函数)。每当你基于这个类创建一个对象时,你就有了一个具体的汽 车,具有这些属性和行为。

C++ 类的基本结构通常包含:

1. 数据成员( Attributes :定义类的属性。这些是类内部的变量,用于存储对象的状态。
2. 成员函数( Methods :定义类的行为。这些是可以操作对象的数据成员的函数。
3. 构造函数和析构函数 :特殊的成员函数。构造函数在创建对象时自动调用,用于初始化对象。析构 函数在对象销毁时调用,用于执行清理操作。
4. 访问修饰符 :如 public , private , protected ,用于控制对类成员的访问权限。例如, public
成员可以在类的外部访问,而 private 成员只能在类内部访问。
5. 继承 :允许一个类继承另一个类的特性。这是代码重用和多态性的关键。
通过这些特性, C++ 类提供了一种强大的方式来组织和处理数据,使得代码更加模块化、易于理解和维 护。

二、 回忆结构体

如果用 C 语言实现上面描述的汽车类,我们实现如下代码
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;

typedef 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);      //函数指针,执行车停止的函数
}Car;

void printCarInfo(string color,string brand,string type, int year)
{
    string str = "车的品牌是:" + brand
            + ",型号是: " + type
            + ",颜色是:" + color
            + ",上市年限是:" + std::to_string(year);
    cout << str << endl;
}

int main()
{
    Car BWMthree;
    BWMthree.color = "白色";
    BWMthree.brand = "宝马";
    BWMthree.type  = "3系";
    BWMthree.year  = 2023;

    BWMthree.printCarInfo = printCarInfo;
    BWMthree.printCarInfo(BWMthree.color,BWMthree.brand,BWMthree.type,BWMthree.year);

    Car *AodiA6 = (struct Car*)malloc(sizeof(struct Car));


    AodiA6->color = "黑色";
    AodiA6->brand = "奥迪";
    AodiA6->type = "A6";
    AodiA6->year = 2008;
    AodiA6->printCarInfo = printCarInfo;

    AodiA6->printCarInfo(AodiA6->color,AodiA6->brand,AodiA6->type,AodiA6->year);

    return 0;
}

C++ 中,通过 std::tostring() 函数,将整型数转化成字符串
printInfo 中使用 cout 输出汽车信息
发现在 C++ 工程中,使用malloc在堆申请结构体空间有问题,所以直接在此引入类的概念

三、引入类

struct 改成class 引入新问题,class 的成员数据和成员函数在不指定权限的情况下,默认 private权限,类的对象无法 进行直接访问,所以需要添加 public属性
main 函数中的原本结构体变量改成了类的实例化,如果变量类型是指针,把原来的 malloc 改成
new 一个对象最后解决了所有问题
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;

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 printCarInfo(string color,string brand,string type, int year)
{
    string str = "车的品牌是:" + brand
            + ",型号是: " + type
            + ",颜色是:" + color
            + ",上市年限是:" + std::to_string(year);
    cout << str << endl;
}

int main()
{
    Car BWMthree;
    BWMthree.color = "白色";
    BWMthree.brand = "宝马";
    BWMthree.type  = "3系";
    BWMthree.year  = 2023;

    BWMthree.printCarInfo = printCarInfo;
    BWMthree.printCarInfo(BWMthree.color,BWMthree.brand,BWMthree.type,BWMthree.year);

    Car *AodiA6 = new Car();


    AodiA6->color = "黑色";
    AodiA6->brand = "奥迪";
    AodiA6->type = "A6";
    AodiA6->year = 2008;
    AodiA6->printCarInfo = printCarInfo;

    AodiA6->printCarInfo(AodiA6->color,AodiA6->brand,AodiA6->type,AodiA6->year);

    return 0;
}

四、真正的成员函数

上面代码中 void (*printCarInfo)(string color,string brand,string type, int year); 到底是变量还是函数函数呢?
实际上它是一个指针变量,是保存某个函数地址的变量,所以它不是成员函数,是成员数据
真正的成员函数遵守封装特性,在函数体内部访问成员数据的时候,不需要参数传递
C++ 中,双冒号 :: 称为 " 作用域解析运算符 " Scope Resolution Operator )。它用于指定一
个成员(如函数或变量)属于特定的类或命名空间。例如,在类的外部定义成员函数时, :: 用于
指明该函数属于哪个类
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;

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();
};

void Car::realPrintCarInfo()
{
    string str = "车的品牌是:" + brand
            + ",型号是: " + type
            + ",颜色是:" + color
            + ",上市年限是:" + std::to_string(year);
    cout << str << endl;
}

void printCarInfo(string color,string brand,string type, int year)
{
    string str = "车的品牌是:" + brand
            + ",型号是: " + type
            + ",颜色是:" + color
            + ",上市年限是:" + std::to_string(year);
    cout << str << endl;
}

int main()
{
    Car BWMthree;
    BWMthree.color = "白色";
    BWMthree.brand = "宝马";
    BWMthree.type  = "3系";
    BWMthree.year  = 2023;
    BWMthree.realPrintCarInfo();

    Car *AodiA6 = new Car();
    AodiA6->color = "黑色";
    AodiA6->brand = "奥迪";
    AodiA6->type = "A6";
    AodiA6->year = 2008;
    AodiA6->printCarInfo = printCarInfo;

    AodiA6->realPrintCarInfo();

    return 0;
}
2.3.4 QT 中经常出现的用法
C++ 中,一个类包含另一个类的对象称为组合( Composition )。这是一种常见的设计模式,用于表示一个类是由另一个类的对象组成的。这种关系通常表示一种" 拥有 " "has-a" )的关系。
普通变量访问成员变量或者成员函数,使用 “ . ” 运算符
指针变量访问成员变量或者成员函数,使用 “ -> ” 运算符,像 C 语言的结构体用法
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;

class Wheel
{
public:
    string brand;
    int year;

    void printWheelInfo();
};

class Car
{
    //汽车“类”
public:
    string color;  //颜色
    string brand;  //品牌
    string type;   //车型
    int year;     //年限

    Wheel wheel;
    Wheel *pwheel;

    //成员函数
    void printCarInfo();
};

void Car::printCarInfo()
{
    string str = "车的品牌是:" + brand
            + ",型号是: " + type
            + ",颜色是:" + color
            + ",上市年限是:" + std::to_string(year);
    cout << str << endl;
}

void Wheel::printWheelInfo()
{
    string str = "轮胎的品牌是:" + brand
            + ",上市年限是:" + std::to_string(year);
    cout << str << endl;
}
int main()
{
    Car BWMthree;
    BWMthree.color = "白色";
    BWMthree.brand = "宝马";
    BWMthree.type  = "3系";
    BWMthree.year  = 2023;
    BWMthree.wheel.brand="米其林";
    BWMthree.wheel.year=2023;
    BWMthree.printCarInfo();
    BWMthree.wheel.printWheelInfo();

    Car *AodiA6 = new Car();
    AodiA6->color = "黑色";
    AodiA6->brand = "奥迪";
    AodiA6->type = "A6";
    AodiA6->year = 2008;
    AodiA6->wheel.brand="普通";
    AodiA6->wheel.year=2024;
    AodiA6->printCarInfo();
    AodiA6->wheel.printWheelInfo();


    return 0;
}


五、权限初识

1 、基本介绍

C++ 中的访问权限主要分为三种: public private protected 。这些权限决定了类成员(包括数 据成员和成员函数)的可访问性。以下是一个总结表格,说明了在不同情况下这些权限如何应用:
使用权限(如 public private protected )在 C++ 中是一种关键的封装手段,它们旨在控制对类 成员的访问。下面是一个表格,总结了使用权限的主要好处和潜在缺点:

2 目前能概况的结论

public 权限相当于我们学习 C 语言结构体一样,不考虑访问权限的存在,但是要注意, 类中不写权
限,默认是私有权限
protected 留到继承讲解的时候再提
private 私有权限,通过一下案例向各位表达一下作用的意思,但需要未来实战中慢慢体会
这个例子将阐述在类设计中使用 private 成员的必要性。我们将创建一个简单的 BankAccount 类,展示
如何使用 private 来保护账户的余额,确保它只能通过指定的方法进行修改
所以,我们可以脑部一个场景:
银行的账户是一个模板,是一个类,有存款人信息和账户额度,而具体的存款人视为一个对象, 一个对象不能私自修改账户额度,需要通过一个操作流程,比如去ATM 或者柜台进行操作才能修改 到账户额度,所以,存款人信息和账户额度设计成私有权限,通过公有的操作流程,也就是公有函数去操作私有 变量。基于这个场景,我们编程实现代码
#include <iostream>
#include <string>
using namespace std;
/*
银行的账户是一个模板,是一个类,有存款人信息和账户额度,而具体的存款人视为一个对象,
一个对象不能私自修改账户额度,需要通过一个操作流程,比如去ATM或者柜台进行操作才能修改到账户额度,
所以,存款人信息和账户额度设计成私有权限,通过公有的操作流程,也就是公有函数去操作私有变量。
基于这个场景,我们编程实现代码
*/
class BankAccount{
private:
    //有存款人信息和账户额度
    string name;
    string addr;
    int age;
    double balance;
public:
    string bankAddr;
    //比如去ATM或者柜台进行操作才能修改到账户额度
    void registerMes(string newName, string newAddr,int newAge,double newBalance);
    void withdrawal(double amount);
    void deposit(double amount);
    double getBalance();
    void printUserInfo();
};
void BankAccount::printUserInfo()
{
    string mesTem = "账户名:" + name + ",地址:" + addr +
    ",年龄:"+ std::to_string(age) + ",存款:" + std::to_string(balance);
    cout << mesTem << endl;
}
void BankAccount::registerMes(string newName, string newAddr,int newAge,double newBalance)
{
    name = newName;
    addr = newAddr;
    age = newAge;
    balance = newBalance;
}
// 存款方法
void BankAccount::deposit(double amount) {
    if (amount > 0) {
    balance += amount;
    cout<<"存款:"<<amount<<endl;
    } else {
    cerr << "Deposit amount must be positive." << endl;
    }
}
// 取款方法
void BankAccount::withdrawal(double amount) {
    if (amount > balance) {
    cerr << "Insufficient funds." << endl;
    } else if (amount <= 0) {
    cerr << "Withdrawal amount must be positive." << endl;
    } else {
    balance -= amount;
    cout<<"取款:"<<amount<<endl;
    }
}
// 获取当前余额的方法
double BankAccount::getBalance() {
    return balance;
}
int main()
{
    BankAccount user1;
    user1.registerMes("小王","湖北襄阳",12,100);
    user1.printUserInfo();
    user1.deposit(1000);
    cout <<"余额:"<< user1.getBalance() << endl;
    user1.withdrawal(30);
    cout <<"余额:"<< user1.getBalance() << endl;
    return 0;
}

 在这个示例中, balance 是一个 private 成员变量,它不能被类的外部直接访问。这保证了账户余额只能通过类提供的方法(如 deposit , withdraw , getBalance )来修改和查询,从而防止了不合适的修改,比如直接设置余额为负数或任意值。这样的设计保证了类的封装性和数据的完整性

六、 提问和回答

问:为什么新手学习C++感受不到访问权限的必要性呢?

答:新手学习 C++ 时可能不会立即感受到访问权限(如 public private protected )的必要性, 主要有以下几个原因:
1. 简单的例子和练习 :初学者通常从简单的例子和练习开始,这些例子可能不需要复杂的封装或继承 结构。在这种情况下,访问权限的作用可能不太明显。
2. 封装的概念需要时间去理解 :封装是面向对象编程中的一个核心概念,但对于初学者来说,理封
装的价值需要一定的时间和实践。在初期,更多的关注点可能放在基本语法和程序结构上。
3. 缺乏大型项目经验 :在小型项目或单文件程序中,访问权限的重要性可能不如在大型、多人协作的 项目中那么显著。在复杂的软件开发中,适当的访问控制对于代码的维护性和可读性至关重要。
4. 直接操作感觉更简单 :对于初学者来说,直接访问和修改类的所有成员可能看起来更简单直接。他 们可能还没有遇到由于不恰当访问控制导致的维护和调试问题。
5. 抽象和设计模式的理解 :理解何时以及如何使用访问权限通常涉及到对软件设计模式和抽象的深入 理解。这些通常是随着经验积累和更深入的学习而逐渐掌握的。随着经验的增长,学习者开始处理更复杂的项目,他们将开始意识到恰当的访问控制的重要性,特别是 在保持代码的可维性、可读性以及在团队环境中的协作方面。因此,对于教育者和学习者来说,强调并实践这些概念是很重要的,以便在编程技能成熟时能够有效地运用它们。
  • 12
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值