Fork me on GitHub

c++之结构体struct和类class的区别

权限的不同:class默认权限为private,struct默认权限为public。

#include<iostream>
using namespace std;

class Student {
    string name;
    int age;
    double score;
};
struct Teacher {
    string name;
    int age;
    void show() {
        cout << "姓名:" << name << endl;
        cout << "年龄:" << age << endl;
    }
};

int main() {
    Student s1;
    /* 此时这样访问会报错
    s1.name = "tom";
    s1.age = 12;
    s1.score = 99.0;
    */
    Teacher t1;
    t1.name = "tom";
    t1.age = 45;
    t1.show();
    system("pause");
    return 0;
}
posted @ 2019-12-24 16:55  西西嘛呦  阅读(419)  评论(0编辑  收藏  举报