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

2020-08-26 15:54:35 浏览数 (1)

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

代码语言:javascript复制
#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;
}

0 人点赞