C++类的定义和封装

#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;
}

原文地址:https://www.cnblogs.com/liming19680104/p/13474593.html