c++类的封装

        

目录

有参构造函数对象

无参数构造函数


封装可是个好东西呢😉 它能让你的代码更简洁、更安全,也更容易维护。就像把你的宝贝都放进一个漂亮的盒子里,不仅整齐好看,还能保护它们不被弄坏🎁。而且啊,封装还能让你更好地控制对象的访问权限,只让别人看到你想让他们看到的,就像魔术师的秘密手法一样🧙‍♂️ 这样能减少出错的可能性,让你的代码更可靠哦!

有参构造函数对象

#include <iostream>
#include <string>

using namespace std;

class Student {
private:
    int age;
public:
    string name;

    Student(string name) {
        this->name=name;//this指针存储着函数调用者的地址 this指向了函数调用者
        cout << "带参数构造函数" << endl;
    }
//    Student() {
//        cout << "无参数构造函数" << endl;
//    }
    void setAge(int age) {
        this->age = age;
    }
    int getAge() {
        return this->age;
    }
};

int main() {
//    Student("gggg");
    Student student("张三");//创建一个名为student的Student类的对象
    student.setAge(18);
    int age = student.getAge();
    string name=student.name;
    cout <<name<< "  age is " << age << endl;
    return 0;
}

无参数构造函数

#include <iostream>
#include <string>

using namespace std;

class Student {
private:
    int age;
public:
    string name;

//    Student(string name) {
//        this->name=name;
//        cout << "带参数构造函数" << endl;
//    }
    Student() {
        cout << "无参数构造函数" << endl;
    }
    void setAge(int age) {
        this->age = age;
    }
    int getAge() {
        return this->age;
    }
};

int main() {
//    Student("gggg");
    Student student;//创建一个名为student的Student类的对象
    student.setAge(18);
    int age = student.getAge();
    student.name="ggg";
    cout <<student.name<< "  age is " << age << endl;
    return 0;
}

 

由于age是私有属性,所以不能直接访问

 

可以定义了两个方法:setAge 用于设置对象的年龄,getAge 用于获取对象的年龄。

在 setAge 方法中,通过 this->age = age; 将传入的参数 age 赋值给对象的成员变量 age

在 getAge 方法中,直接返回对象的成员变量 age

student.setAge(18);
int age = student.getAge();

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西柚与蓝莓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值