C++ 类的保护基

C++ 类的保护基,c++,class,oop,C++,Class,Oop,在第16行中,当我使用public时,它可以工作,但当我尝试使用protected基类型时,它会给我一个编译错误。有人能给我简单解释一下吗。 我假设这是因为基类的受保护成员类似于私有成员,但我不确定 #include <iostream> #include <string> using namespace std; // base class class College { //private: protected: string name; publ

在第16行中,当我使用
public
时,它可以工作,但当我尝试使用
protected
基类型时,它会给我一个编译错误。有人能给我简单解释一下吗。 我假设这是因为基类的受保护成员类似于私有成员,但我不确定

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


// base class
class College
{
    //private:
protected:
    string name;
public:
    College(string name = "any college")
    { this->name = name; cout << "base College constructor\n"; }
    ~College() { cout << "base College destructor\n"; }
    string getName() const { return name; }
};

// derived class
class CommunityCollege : protected College //(public college it works)
{
private:
    string district;
public:
    CommunityCollege(string name, string district) : College(name)
    { this->district = district; cout << "derived Community College constructor\n"; }
    ~CommunityCollege() { cout << "derived Community College destructor\n"; }
    string getDistrict() const { return district; }
    void printName() const { cout << name << endl; }

};

class FHDA : public CommunityCollege
{
private:
    int numStudents;
public:
    FHDA(string name, string district, int num) : CommunityCollege (name, district)
    { this->numStudents = num; cout << "derived 2 FHDA constructor\n"; }
    ~FHDA() { cout << "derived 2 FHDA destructor\n"; }
    int getStudentNum() const { return numStudents; }
};

int main()
{

     /////////////////////// Part 1: inheritance basics //////////////////////

     CommunityCollege da ("foothill", "fhda");
     cout << da.getName() << endl;
return 0;
}
#包括
#包括
使用名称空间std;
//基类
班级学院
{
//私人:
受保护的:
字符串名;
公众:
学院(string name=“任何学院”)

{this->name=name;cout受保护的成员对于不是从该类派生的所有对象都像private一样,但是当其他一些类继承具有受保护成员的类时,它可以作为public进行访问。

编译示例时会出现错误:

main.cpp: In function ‘int main()’:
main.cpp:16:12: error: ‘std::string College::getName() const’ is inaccessible
     string getName() const { return name; }
            ^
main.cpp:50:25: error: within this context
      cout << da.getName() << endl;
                         ^
main.cpp:50:25: error: ‘College’ is not an accessible base of ‘CommunityCollege’
main.cpp:在函数“int main()”中:
main.cpp:16:12:错误:“std::string College::getName()const”不可访问
字符串getName()常量{return name;}
^
main.cpp:50:25:错误:在此上下文中

这被称为受保护的继承。 简单地说,受保护的继承只对底层阶级及其子女可见。从外部世界看,没有人能看出社区学院是否起源于大学

如果希望使用基类中的某些函数,可以在派生类的公共声明中使用using声明:

using College::getName;