zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++类的定义和封装

C++封装 定义
2023-09-27 14:28:42 时间

定义类的格式:

class 类名:继承方式 基类,......{    }

#include <iostream>
#include <string>
using namespace std;

class Student {
    //类默认都是私有的
    //成员
private:
    string name;
public:
    int age;
    int no;
    //成员函数

    void Name(const string& newname) {
        name = newname;
    }
    /*
    利用公有函数对私有成员进行访问---封装
    */
    void eat(const string& food) {
        cout << "我在吃" << food << endl;
    }
    void sleep(int hour) {
        cout << "我睡了" << hour << "小时" << endl;
    }
    void learn(const string& course) {
        cout << "我在学" << course << endl;
    }
    void who(void) {
        cout << "我叫" << name << endl;
        cout << "今年" << age << "" << endl;
        cout << "学号是:" << no << endl;
    }
};

int main()
{
    Student s;
    s.Name("张三");
    s.age = 25;
    s.no = 10011;
    s.who();
    s.eat("牛肉拉面");
    s.sleep(8);
    s.learn("C++编程");
    return 0;
}