C++学习笔记10——类和封装

本文介绍了C++中类的定义及使用class与struct关键字的区别,重点讲解了成员变量与成员函数的不同访问级别,并通过示例代码展示了如何实现封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class关键字

  • 在C++中提供新的关键字class用于类定义

  • C++中classstruct用法是完全相同的

  • classstruct的区别在于:

    • 在使用struct定义类时, 所有成员的默认访问级别public

    • 在使用class定义类时, 所有成员的默认访问级别private

类的封装

封装的概念

  • 类的属性和行为有些可以对外公开,有些不对外公开
  • 必须在类的表示法中定义属性和行为的公开级别

C++中类的封装

  • 成员变量:C++中用于表示类属性的变量

  • 成员函数:C++中用于表示类行为的函数

  • C++中可以给成员变量成员函数定义访问级别

    • public:

      • 成员变量和成员函数可以在类的内部和外界访问和调用
    • private:

      • 成员变量和成员函数只能在类的内部被访问和调用
/*
    测试代码
*/

#include <stdio.h>

class Girl
{
private:
    int age;
    int weight;
public:
    void print()
    {
        age = 22;
        weight = 48;

        printf("I'm a girl, I'm %d years old.\n", age);
        printf("My weight is %d kg.\n", weight);
    }
};

class Boy
{
private:
    int height;
    int salary;
public:
    int age;
    int weight;

    void print()
    {
        height = 175;
        salary = 9000;

        printf("I'm a boy, my height is %d cm.\n", height);
        printf("My salary is %d RMB.\n", salary);
    }
};

int main()
{
    Girl g;
    Boy b;

    g.print();

    b.age = 19;
    b.weight = 120;

    //b.height = 180;       // height is private

    b.print();

    return 0;
}

运行结果

I'm a girl, I'm 22 years old.
My weight is 48 kg.
I'm a boy, my height is 175 cm.
My salary is 9000 RMB.

类成员的作用域

  • 类成员的作用域都只在类的内部外部无法直接访问

  • 成员函数可以直接访问成员变量调用成员函数

  • 类的外部可以通过类变量访问public成员

  • 类成员的作用域与访问级别没有关系

/*
    测试代码
*/

#include <stdio.h>

int i = 1;

class Test
{
private:
    int i;

public:
    int j;

    int getI()
    {
        i = 3;

        return i;
    }
};

int main()
{
    int i = 2;

    Test test;

    test.j = 4;

    printf("i = %d\n", i);              // i = 2;

    printf("::i = %d\n", ::i);          // ::i = 1;

    // printf("test.i = %d\n", test.i);    // Error

    printf("test.j = %d\n", test.j);    // test.j = 4

    printf("test.getI() = %d\n", test.getI());  // test.getI() = 3

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值