0
点赞
收藏
分享

微信扫一扫

面向对象总结1

秀妮_5519 2022-03-11 阅读 55

        面向对象的时代开启了,也算是预习一下新的功课吧,算是一个小小的总结,结束今天的面向对象的程序学习。

1.构造函数/析构函数/拷贝函数

//构造函数,析构函数,拷贝函数
#include <iostream>
using namespace std;
class Phone {//新构造一个类
public:
    Phone(string name) {
        m_phonename = name;
    }
    ~Phone()
    {
        cout << "Phone析构" << endl;
    }
    string m_phonename;
};
class Person {
public:
    Person(string name, string pname) :m_name(name), m_phone(pname) {
        cout << "Person的构造函数" << endl;//构造函数
        
    }
    ~Person()
    {
        cout << "Person的析构函数" << endl;
    }
    void playgame() {
        cout << m_name << "的" << m_phone.m_phonename << "的手机" << endl;//调用m_phone里面的属性
    }
    string m_name;
    Phone m_phone;
};
void test01() {
    Person p("张华","苹果");
    p.playgame();
}

int main()
{
    test01();
}

2.this指针的应用场景

This 指针
//this指针的用途,this空指针,const修饰成员函数
#include <iostream>
using namespace std;
//this指针的一些小小的用途。
//1.解决名称冲突
class Person {
public:
    Person(int age) {//构造函数
        //age = age名称冲突,默认函数参数与类参数一致
        this->age = age;
    }
    //2.返回对象本身可以用*this
    Person& PersonAddage(Person& p) {//引用Person本体这个函数
        this->age += p.age;//累加年龄
        return *this;//*this指的就是p2这个整体,因为返回值是指向p的指针,所以也要引用Person.
    }
    //空指针的操作问题
    void showPersonAge() {
        if (this == NULL) {
            return;//空指针就直接返回,增加程序的健壮性
        }
        cout << "年龄为:" << this->age << endl;
    }
    int age;
};
void test01() {
    Person p1(18);
    Person p2(20);
    p2.PersonAddage(p1).PersonAddage(p1).PersonAddage(p1);//链式结构的一种
    cout << "p2的年龄为:" << p2.age << endl;
}
void test02() {
    Person* p=NULL;//空指针
    p->showPersonAge();
}
int main()
{
    //test01();
test02();}

        注:注意*this的使用。

3.const常量的使用

Const 修饰成员函数
#include <iostream>
using namespace std;
class Person {
public:
    //this指针的本质是指针常量,指针的指向是不可以修改的
    void showPerson()const {//加入const指针的值也是不可以改变的
        //this->m_a=100;不能改变值,不能改变成员属性
        this->m_b = 100;//加上mutable即可修改指针b的值
    }
    void fun() {
        cout << "很好,很好" << endl;
    }
    int m_a;
    mutable int m_b;
};
void test02() {
    const Person p;//在对象面前加const,定义为常对象。
    //p.m_a = 100;
    p.m_b = 100;//常对象只能定义常对象
    p.showPerson();//常对象只能调用常量函数
    //p.fun();不能调用其它函数
    Person p2;
    p2.fun();

}
int main()
{
    test02();
}

        就是根据*马教程写的,好好学习,天天向上,不得不承认今天确实有点水但是今天功课比较紧,一会还要看算法书,面向对象会持续更新的。

举报

相关推荐

0 条评论