C++的对象和类

2019-02-27  本文已影响0人  Airjoden

public:public表明该数据成员、成员函数是对所有用户开放的,所有用户都可以直接进行调用
private:private表示私有,意思就是除了class自己之外,任何人都不可以直接调用,即便是继承后,子女,朋友,都不可以调用。
protected:protected对于子女、朋友(内部)来说,就是public的,可以自由调用,没有任何限制,而对于其他的外部class,protected就变成private不能调用。

自己的感悟:一开始觉得C++的类和结构体很像,其实它们的区别就是类在建立的时候里面的元素可以是函数而结构体不可以。

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

class Student {
    private:
        char name[20];
        char sex;
    protected:
        int num;
    public:
        
        void display(){
            cout << "num: " << num << endl;
            cout << "name: " << name << endl;
            cout << "sex: " << sex << endl;
        }
        void setData(char* n, char s, int nu) {
            strcpy(name, n);
            sex = s;
            num = nu;
        }
};


class Member: public Student {
    private:
        char type[20];
    public:
        void showType() {
            cout << "type: " << type << endl;
            cout << "num: " << num << endl;  //受保护的不可再外域访问,可以在继承中访问
            // cout << "sex: " << sex << endl; //私有的不可访问
        }
        void setType(char* t) {
            strcpy(type, t);
        }
};


int main() {
    Student stu1;
    stu1.setData("lihongji", 'm', 202);
    stu1.display();
    // cout << stu1.num << endl;  //不能访问
    cout << "--------------------" << endl;
    Member mem1, mem2;
    mem1.setData("Aj", 'm', 202);
    mem1.setType("basketball");
    // mem1.display();
    mem1.showType();
    cout << "--------------------" << endl;
    // mem2.setData("Amy", 'f', 101);
    // mem2.setType("urben");
    // mem2.display();
    // mem2.showType();
    // cout << "--------------------" << endl;
    // cout << mem2.num << endl;
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读