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



















