【C++总结】04:类与对象

类与对象


一、对象初始化与清理:

cpp中的面向对象来源于生活,每个对象都有初始设置以及对象销毁前数据清理的设置。(使用构造函数与析构函数实现)

1.构造/析构函数:
  • 构造函数:用于在创建对象时为对象的成员属性赋值,构造函数由编译器自动调用。格式:类名(){...}
构造函数特点
1.构造函数没有返回值,也不用书写void
2.构造函数的名称与类名相同
3.构造函数可以有参数,故可以发生重载
4.程序在调用对象时会自动调用构造,无须手动调用(并且只会调用一次)
  • 析构函数:用于在对象销毁前系统自动调用,执行一些清理工作。格式:~类名(){...}
析构函数特点
1.构造函数没有返回值,也不用书写void
2.构造函数的名称与类名相同,并在名称前加上符号~
3.构造函数不可以有参数,故不可以发生重载
4.程序在对象销毁前会自动调用析构,无须手动调用(并且只会调用一次)
#include <iostream>
using namespace std;

//对象的初始化与清理
class Person{
public:
    //1.构造函数进行初始化操作
    Person() {
        cout << "Person的构造函数被调用" << endl;
    }
    //2.析构函数进行清理操作
    ~Person() {
        cout << "Person的析构函数被调用" << endl;
    }
};

void test01() {
    Person p;//在栈上的数据在test01执行完毕之后就会被释放
}

int main() {
    test01();
    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M0lbeiP1-1672576681580)(null)]

2.构造函数的分类及调用:
  • 构造函数分类有:有参构造、无参构造、普通构造和拷贝构造。
  • 构造函数有三种调用方式:括号法、显示法、隐式转换法
#include <iostream>
using namespace std;

//1.构造函数的分类
class Person {
public:
    //(1)构造函数
    Person(){
        cout << "Person的无参(默认)构造函数调用" << endl;
    }
    Person(int a){
        age = a;
        cout << "Person的有参构造函数调用" << endl;
    }
    //(2)拷贝构造函数
    Person(const Person &p){
        cout << "Person的拷贝构造函数调用" << endl;
        age = p.age;//将传入对象实例的所有属性进行拷贝
    }
    ~Person(){
        cout << "Person的析构函数调用" << endl;
    }
    int age;
};

//2.构造函数的调用
void test01(){
    //(1)括号法
    Person p1;//默认构造函数调用,注意:调用默认构造函数时不需要添加括号,否则将被编译器认为是一种函数声明
    Person p2(10);//有参构造函数调用
    Person p3(p2);//拷贝构造函数调用
    cout << "p2的年龄为:" << p2.age << endl;
    cout << "p3的年龄为:" << p3.age << endl;
}

void test02(){
    //(2)显示法(对匿名对象进行命名)
    Person p1;
    Person p2 = Person(10);//有参构造
    Person p3 = Person(p2);//拷贝构造
    //显示法右侧的Person(10)被称为匿名对象,特点:当前执行结束后,系统会立即回收匿名对象
    //注意:不要利用拷贝构造函数Person(p3);来初始化匿名对象,因为Person(p3) === Person p3(重复创建p3对象);
    cout << "p2的年龄为:" << p2.age << endl;
    cout << "p3的年龄为:" << p3.age << endl;
}

void test03(){
    //(3)隐式转换法
    Person p1;
    Person p2 = 10;//相当于写了Person p4 = Person(10);
    Person p3 = p2;//拷贝构造
    cout << "p2的年龄为:" << p2.age << endl;
    cout << "p3的年龄为:" << p3.age << endl;
}

int main() {
    test01();
    test02();
    test03();

    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xmvEsnr4-1672576681438)(null)]

注意:

  1. 调用默认构造函数时不需要添加括号,否则将被编译器认为是一种函数声明。
  2. 不要利用拷贝构造函数Person(p3);来初始化匿名对象,因为Person(p3) === Person p3(重复创建p3对象)
3.构造函数调用规则:

规则1:创建一个类,c++编译器会给每个类都添加至少3个函数(默认构造-空实现、析构函数-空实现、拷贝构造-值拷贝)

#include<iostream>
using namespace std;

class Person{
public:
    //(1)默认构造函数
    Person(){
        cout << "Person的默认构造函数调用" << endl;
    }
    //(2)有参构造函数
    Person(int a){
        cout << "Person的有参构造函数调用" << endl;
        age = a;
    }
    //(4)析构函数
    ~Person(){
        cout << "Person的析构函数调用" << endl;
    }
    int age;
};

void test01(){
    Person p;
    p.age = 18;

    Person p2(p);
    cout << "p2的年龄为:" << p2.age << endl;
}

int main() {
    test01();
    system("pause");
    return 0;
}

image-20220119184552105

#include<iostream>
using namespace std;

class Person{
public:
    //(1)默认构造函数
    Person(){
        cout << "Person的默认构造函数调用" << endl;
    }
    //(2)有参构造函数
    Person(int a){
        cout << "Person的有参构造函数调用" << endl;
        age = a;
    }
    //(3)拷贝构造函数
    Person(const Person &p){
        cout << "Person的拷贝构造函数调用" << endl;
        age = p.age;
    }
    //(4)析构函数
    ~Person(){
        cout << "Person的析构函数调用" << endl;
    }
    int age;
};

void test01(){
    Person p;
    p.age = 18;

    Person p2(p);
    cout << "p2的年龄为:" << p2.age << endl;
}

int main() {
    test01();
    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-A5TjoixK-1672576681469)(null)]

如果用户没有对拷贝构造函数进行自定义,编译器会对对象进行简单的值拷贝(对所有的属性进行拷贝age = p.age;

规则2:如果用户定义有参构造函数,则c++不再提供默认无参构造(但是依然会提供拷贝构造)

#include<iostream>
using namespace std;

class Person{
public:
    //(2)有参构造函数
    Person(int a){
        cout << "Person的有参构造函数调用" << endl;
        age = a;
    }
    //(3)拷贝构造函数
    Person(const Person &p){
        cout << "Person的拷贝构造函数调用" << endl;
        age = p.age;
    }
    //(4)析构函数
    ~Person(){
        cout << "Person的析构函数调用" << endl;
    }
    int age;
};

//1.如果用户定义有参构造函数,则编译器就不再提供默认无参构造(但是依然会提供拷贝构造)
void test02(){
    Person p;
}

int main() {
    test02();
    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3OspZCMi-1672576681611)(null)]

注意:由于用户自定义了有参构造函数,则编译器不再提供默认无参构造函数。故最后导致程序报错。

规则3:如果用户定义拷贝构造函数,则c++不会再提供其他普通构造函数(默认构造 & 有参构造)

4.拷贝构造函数调用时机:

cpp中拷贝构造函数调用时机通常有三种情况:

  1. 使用一个已经创建的对象来初始化一个新对象
  2. 使用值传递的方式给函数参数传值
  3. 使用返回值的方式返回局部对象
#include<iostream>
using namespace std;

class Person{
public:
    Person(){
        cout << "Person默认构造函数调用" << endl;
    }
    Person(int a) {
        cout << "Person有参构造函数调用" << endl;
        age = a;
    }
    Person(const Person &p){
        cout << "Person拷贝构造函数调用" << endl;
        age = p.age;
    }
    ~Person(){
        cout << "Person析构函数调用" << endl;
    }
    int age;
};

//1.使用一个已经创建的对象来初始化一个新对象
void test01(){
    cout << "test01" << endl;
    Person p1(20);
    Person p2(p1);
    cout << "p1的年龄为:" << p1.age << endl;
    cout << "p2的年龄为:" << p2.age << endl;
}

//2.值传递的方式给函数参数传值
void doWork(Person p){}
void test02(){
    cout << "test02" << endl;
    Person p3;
    doWork(p3);
}

//3.返回值的方式返回局部对象
Person doWork2(){
    Person p1;
    cout << (int*)&p1 << endl;
    return p1;
}
void test03(){
    cout << "test03" << endl;
    Person p = doWork2();
    cout << (int*)&p << endl;
}

int main() {
    test01();
    test02();
    test03();
    system("pause");
    return 0;
}

image-20220119173228645

5.深拷贝&浅拷贝:

浅拷贝:简单的赋值拷贝操作

深拷贝:在堆区重新申请空间,进行拷贝操作

#include<iostream>
using namespace std;

class Person{
public:
    Person(){
        cout << "Person的默认构造函数调用" << endl;
    }
    Person(int a, int h){
        age = a;
        height = new int(h);//在堆区创建内存存放身高,并用height指针接收地址
        cout << "Person的有参构造函数调用" << endl;
    }
    ~Person(){
        if (height != NULL){
            delete height;//释放内存
            height = NULL;//防止野指针出现
        }
        cout << "Person的析构函数调用" << endl;
    }
    int age;
    int *height;
};

void test01(){
    Person p1(18, 160);
    cout << "p1的年龄为:" << p1.age << "身高为:" << *p1.height << endl;
    Person p2(p1);
    cout << "p2的年龄为:" << p2.age << "身高为:" << *p2.height << endl;
}

int main(){
    test01();
    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pdgbO4Wm-1672576681527)(null)]

堆区内存重复释放导致程序出错

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mQGkJ6RK-1672576681499)(null)]

image-20220119201548517

#include<iostream>
using namespace std;

class Person{
public:
    Person(){
        cout << "Person的默认构造函数调用" << endl;
    }
    Person(int a, int h){
        age = a;
        height = new int(h);//在堆区创建内存存放身高,并用height指针接收地址
        cout << "Person的有参构造函数调用" << endl;
    }
    //自定义拷贝构造函数,解决浅拷贝带来的问题(深拷贝)
    Person(const Person &p) {
        age = p.age;
        //对编译器浅拷贝默认实现的height = p.height;进行重定义
        height = new int(*p.height);
        cout << "Person拷贝构造函数的调用" << endl;
    }
    ~Person(){
        if (height != NULL){
            delete height;//释放内存
            height = NULL;//防止野指针出现
        }
        cout << "Person的析构函数调用" << endl;
    }
    int age;
    int *height;
};

void test01(){
    Person p1(18, 160);
    cout << "p1的年龄为:" << p1.age << "身高为:" << *p1.height << endl;
    Person p2(p1);
    cout << "p2的年龄为:" << p2.age << "身高为:" << *p2.height << endl;
}

int main(){
    test01();
    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0MonhCQh-1672576681640)(null)]

使用深拷贝解决堆区内存重复释放问题后,程序能够正常的执行。

总结:如果属性有在堆区开辟内存的,一定需要自定义拷贝构造函数(深拷贝),防止浅拷贝带来的内存重复释放问题。

6.对象初始化:
  • 作用:c++中提供了初始化列表语法,用来初始化类对象的属性。
  • 语法:构造函数():属性1(值1),属性2(值2)...{}
#include<iostream>
using namespace std;

class Person{
public:
    //1.传统的初始化操作
    Person(int x, int y, int z){
        a = x;
        b = y;
        c = z;
    }
    int a;
    int b;
    int c;
};

void test01(){
    Person p(10, 20, 30);
    cout << "a = " << p.a << endl;
    cout << "b = " << p.b << endl;
    cout << "c = " << p.c << endl;
}

int main(){
    test01();

    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L7jgsoA5-1672576681553)(null)]

#include<iostream>
using namespace std;

class Person{
public:
    //2.初始化列表初始化属性
    Person(int x, int y, int z):a(x), b(y), c(z){}
    int a;
    int b;
    int c;
};

void test01(){
    Person p(10, 20, 30);
    cout << "a = " << p.a << endl;
    cout << "b = " << p.b << endl;
    cout << "c = " << p.c << endl;
}

int main(){
    test01();

    system("pause");
    return 0;
}

image-20220119204027336

7.对象作为类成员:

c++类中的成员可以是另一个类的对象,被称为对象成员。

#include<iostream>
using namespace std;

class Phone{
public:
    Phone(string t){
        cout << "Phone的构造函数调用" << endl;
        type = t;
    }
    ~Phone(){
        cout << "Phone的析构函数调用" << endl;
    }
    string type;
};

class Person{
public:
    Person(string n, string t):name(n), phone(t){
        cout << "Person的构造函数调用" << endl;
    }
    ~Person(){
        cout << "Person的析构函数调用" << endl;
    }
    string name;
    Phone phone;
};

void test01(){
    Person p("lch", "iphone13 pro");
    cout << p.name << "买了一部" << p.phone.type << endl;
}

int main() {
    test01();
    system("pause");
    return 0;
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6jIbLZU7-1672576681669)(null)]

总结:当其他类对象作为本类成员时

  1. 构造时先构造Phone类,再构造Person类(先构造类对象,再构造自身)
  2. 析构时先析构Person类,再析构Phone类(先析构自身,再析构类对象)
8.静态成员:

静态成员即在成员变量和成员函数前加上关键字static,则被称为静态成员,静态成员分为静态成员变量&静态成员函数:

静态成员变量

  1. 静态成员变量需要在类内进行声明、类外初始化
  2. 静态成员变量不属于某个对象,所有的对象共享同一份数据
  3. 静态成员变量在编译阶段分配内存
#include<iostream>
using namespace std;

class Person{
public:
    static int a;//类内声明
};

int Person::a = 100;//类外初始化

void test01(){
    Person p1;
    cout << p1.a << endl;
}

void test02(){
    Person p2;
    p2.a = 200;//所有对象共享同一份数据(将共享的a数据从100修改为200)
    cout << p2.a << endl;
}

void test03(){
    //静态成员变量有两种访问方式
    //1.通过类的某一个对象进行访问
    Person p3;
    cout << p3.a << endl;
    //2.直接通过类名进行访问
    cout << Person::a << endl;
}

int main(){
    test01();
    test02();
    test03();

    system("pause");
    return 0;
}

静态成员函数

  1. 所有对象共享同一个函数
  2. static静态成员函数只能访问静态成员变量
#include<iostream>
using namespace std;

class Person{
public:
    static void func(){
        a = 100;
        cout << "static void func的调用" << endl;
    }
    int b;
    static int a;
};

int Person::a = 0;

void test01(){
    //1.通过类的某一个对象调用
    Person p;
    p.func();
    //2.直接通过类名进行调用
    Person::func();
}

int main(){
    test01();
    system("pause");
    return 0;
}

二、对象模型和this指针

1.成员变量和成员函数分开存储:

在C++中,类内的成员变量和成员函数是分开存储的,只有非静态成员变量才属于类的对象上。

#include<iostream>
using namespace std;

//成员变量和成员函数 分开存储
class Person{
    int a;//非静态成员变量,属于类的对象上
    static int b;//静态成员变量,不属于类对象上
    void func1(){}//非静态成员函数,不属于类对象上
    static void func2(){}//静态成员函数,不属于类对象上
};

void test01(){
    Person p;
    //1.空对象占用内存空间为:1bit字节
    //2.C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占用内存的位置
    //3.每个空对象也应该有一个独一无二的内存地址
    cout << "size of p = " << sizeof(p) << endl;
}

void test02(){
    Person p;
    //1.空对象占用内存空间为1bit字节
    //2.C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占用内存的位置
    //3.每个空对象也应该有一个独一无二的内存地址
    cout << "size of p = " << sizeof(p) << endl;
}

int main(){
    test01();
    test02();
    system("pause");
    return 0;
}

​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QhxsyCAS-1672576681695)(null)]

2.this指针概念:

由于成员变量与成员函数是分开存储的,每一个非静态成员函数只会诞生一份函数实例(多个同类型对象会公用一块代码)

c++提供了特殊的对象指针this,this指针指向被调用的成员函数所属的对象。

需要注意:

  1. this指针隐含在每一个非静态成员函数内的一种指针
  2. this指针不需要定义,直接使用即可

this指针用途:

  1. 当参数与成员变量同名时,可用this指针来区分(解决名称冲突)
  2. 类的非静态成员函数返回对象本身,可使用return *this(返回对象本身用*this)
#include<iostream>
using namespace std;

class Person{
public:
    Person(int age){
        this->age = age;//this指针指向的是被调用的成员函数所属的对象
    }
    Person PersonAddAge(Person &p){
        this->age += p.age;
        return *this;//this指向p2的指针
    }
    Person& PersonAddAge_refer(Person &p){
        this->age += p.age;
        return *this;//this指向p2的指针
    }
    int age;
};

//1.解决名称冲突
void test01(){
    Person p1(18);
    cout << "p1的年龄为:" << p1.age << endl;
}

//2.返回对象本身用*this
void test02(){
    Person p1(10);
    Person p2(20);
    p2.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
    cout << "返回值时p2的年龄为:" << p2.age << endl;
    p2.PersonAddAge_refer(p1).PersonAddAge_refer(p1).PersonAddAge_refer(p1);
    cout << "返回引用时p2的年龄为:" << p2.age << endl;
    //返回值时调用拷贝构造,会自动创建一个新的对象
}

int main(){
    test01();
    test02();

    system("pause");
    return 0;
}

注:在返回对象本身使用*this时,返回&Person与返回Person的区别在于是否会调用拷贝构造函数创建新的对象

3.空指针访问成员函数:

c++中空指针也是可以调用成员函数的,但需要注意有没有用到this指针(如果用到this指针需要加以判断保证代码的健壮性

#include<iostream>
using namespace std;

class Person{
public:
    void showClassName(){
        cout << "this is Person class" << endl;//1.空指针可以正常访问成员函数
    }
    void showPersonAge(){
        if(this == NULL) return;
        cout << "age = " << age << endl;//2.this->age,传入的指针为空时会直接导致报错
    }
    int age;
};

void test01(){
    Person *p = NULL;
    p->showClassName();
    p->showPersonAge();
}

int main(){
    test01();

    system("pause");
    return 0;
}
4.const修饰成员函数:

常函数:成员函数后加上const后被称为常函数

注:

  1. 常函数内不可以修改成员属性
  2. 成员属性添加mutable后,在常函数、常对象中可以修改

常对象:声明的对象前加上const称该对象为常对象

注:常对象只能调用常函数

#include<iostream>
using namespace std;

class Person{
public:
    Person(){}
    Person(int n){}
    //this指针本质为指针常量Person * const this,指针的指向是不可修改的
    //1.在成员函数后面添加const,修饰的是this指针的指向、让指针指向的值也不可修改
    void showPerson() const{
        //a = 100;//this->a = 100;报错
        b = 200;//this->b = 200;
        cout << "showPerson()常函数被调用" << endl;
    }
    void func(){}
    int a;
    mutable int b;//2.成员属性添加mutable后,在常函数、常对象中可以修改
};

//常函数测试test01
void test01(){
    Person p1;
    p1.showPerson();//常函数不允许修改this指针指向的值
}

//常对象测试test02
void test02(){
    const Person p2(2);//常对象不允许修改this指针指向的值
    //p2.a = 100;报错
    p2.b = 200;
    //3.常对象只能调用常函数
    //p2.func();报错
    p2.showPerson();
}

int main(){
    test01();
    test02();
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值