c++和delphi差不多,在类内都有三种访问权限

1.public 公共权限 类内可以访问,类外可以访问

2.protected 保护权限 类内可以访问,类外不可访问

3.private 私有权限 类内可以访问,类外不可访问且不能继承

class和struct的区别

在于默认的访问权限不同,其他都一样,class默认是私有的,而struct默认是公共的.

#include<iostream>
#include<string>
using namespace std;

class Student {
protected:
    string name;
    int id;

public:

    Student() {     //构造函数 1.没有返回值,也不写void  2.函数名称与类名称一致  3.构造函数可以有参数,所以可以重载    
                    //4.程序在调用对象的时候会自动调用构造函数,仅1次,无需手动调用
        name = "老王";
        id = 1;
    }

    int Showid() {
        return id;
    }
    void ShowMessage() {
        cout << "姓名:" << name << "\tid:" << id << endl;
    }
    ~Student() {      //析构函数  1.没有返回值也不写void   2.与类名相同前面加一个~符号   
                      //3.析构函数不能有参数,也不能重载   4.对象销毁前会自动调用1次,无需手动调用
        cout << "析构函数了" << endl;
    }

};

int main() {
    Student s1;
    s1.ShowMessage();
    system("pause");
}
最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏