C++类的定义和封装

定义类的格式:

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

 

 

 

 

C++类的定义和封装

相关文章:

  • 2021-11-19
  • 2021-05-22
  • 2021-09-28
  • 2021-08-03
  • 2021-12-06
  • 2021-12-16
  • 2021-12-12
  • 2021-05-17
猜你喜欢
  • 2022-12-23
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2021-08-22
  • 2021-06-20
  • 2022-12-23
相关资源
相似解决方案