C嘎嘎 - 类和对象

1. 封装

(1)语法

        class 类名{ 访问权限 : 属性 / 行为 };

class Circle
{
public:   // 访问权限
    int r;
    double s;
    
    double sq(){
        return 2*r*s;
    }        
};

int main()
{
    Circle c1;
    c1.r = 2;
    c1.s = 2.1;
    c1.sq();
}

(2)构造函数和析构函数

    01 构造函数语法:类名() {};可以重载;没有返回值也不写void;

    02 析构函数语法:~类名(){};不可以重载;没有返回值也不写void;

    03 对象的初始化和清理:构造函数进行初始化操作,析构函数进行清理操作。

class Person
{
    Person()
    {
        cout << "构造函数的调用" << endl;
    }

    ~Person()
    {
        cout << "析构函数的调用" << endl;
    }
};

(3)构造函数的分类和调用

    01 分类:

        001 按参数分为:有参构造和无参构造(默认)

        002 按类型分为:普通构造和拷贝构造

class Person
{
    Person (int a)
    {
        age = a;
        cout << "有参构造函数的调用" << endl;
    }

    // 拷贝构造函数
    Person(const Person &p)
    {
        age = p.age; 
    }   

    int age;
};

    02 三种调用方式:

        001 括号法

        002 显示法

        003 隐式转换法

class Person
{
    Person()
    {
        cout << "无参构造函数的调用" << endl;
    }

    Person (int a)
    {
        age = a;
        cout << "有参构造函数的调用" << endl;
    }

    // 拷贝构造函数
    Person(const Person &p)
    {
        age = p.age; 
        cout << "拷贝构造函数的调用" << endl;
    }   

    int age;
};

//括号法
void test01()
{
    Person p1;      //默认构造函数调用
    Person p2(10);  //有参构造函数调用
    Person p3(p2);  //拷贝构造函数调用    
};

//显示法
void test01()
{
    Person p1;                  //默认构造函数调用
    Person p2 = Person p2(10);  //有参构造函数调用
    Person p3 = Person p3(p2);  //拷贝构造函数调用   
};

 (4)初始化列表

    01 语法:构造函数() : 属性1(值1),  属性2(值2)……{}

    

class Person
{
    // 传统初始化方式
    Person (int a, int b, int c)
    {
        M_a =a;
        M_b =b;
        M_c =c;
    }

    // 初始化列表初始化属性
    Person(int a, int b, int c) : M_a(a), M_b(b), M_c(c) {}
    
    int M_a;
    int M_b;
    int M_c;
};

void test()
{
    Person p(10, 20, 30);
    cout << M_a << M_b << M_c << endl;
};

2. 继承

(1)语法

     class 子类名称 : 继承方式 父类名称{……};

class Person
{
public:
    int age;
    string name;
};

class Student : public Person
{
public:
    cout<< "独有的" << endl;
};

(2)多继承语法

    class 子类 : 继承方式 父类1,   继承方式 父类2,  ……

class Person
{
public:
    int age;
    string name;
};

class People
{
public:
    int age;
    string name;
};

class Student : public Person, public People
{
public:
    cout<< "独有的" << endl;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值