C++-class struct(类)

class和struct的区别就是class需要指明private 和 public 而 struct不需要

/*
类定义
*/ 
#include <iostream>

using namespace std; 

struct Student {
public:
    void eat(const string& food) {
        cout << "我在吃" << food << endl; 
    }
    void sleep(const int hour) {
        cout << "我睡了" << hour << "小时" << endl; 
    }
    void study(const string& course) {
        cout << "我学习" << course << endl; 
    }
    void who(void) {
        cout << "我是" << m_name << ",今年" << m_age << "岁,编号" << m_no << endl; 
    }
    void set_name(const string& name) {
        m_name = name; 
    }
    void set_age(const int age) {
        m_age = age; 
    }
    void set_no(const int no) {
        m_no = no; 
    }

private:
    string m_name; 
    int m_age; 
    int m_no;  
};

int main(void) {
    Student s; 
    s.set_name("小明"); 
    s.set_age(12); 
    s.set_no(10001); 
    s.eat("饺子");
    s.sleep(12); 
    s.study("语文");  
    s.who(); 
}

猜你喜欢

转载自www.cnblogs.com/hyq-lst/p/12603735.html