Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用派生类对象从基类访问受保护的函数_C++_Inheritance_Protected - Fatal编程技术网

C++ 使用派生类对象从基类访问受保护的函数

C++ 使用派生类对象从基类访问受保护的函数,c++,inheritance,protected,C++,Inheritance,Protected,嗨,我有下面的代码,我在其中使用受保护的继承 #include<iostream> #include<string> using namespace std; class Animal { protected: int age; string name; public: void setAge(int a) { this->age = a; } void setName(string n)

嗨,我有下面的代码,我在其中使用受保护的继承

#include<iostream>
#include<string>

using namespace std;

class Animal
{
protected:
    int age;
    string name;
public:
    void setAge(int a)
    {
        this->age = a;
    }
    void setName(string n)
    {
        this->name = n;
    }
    int getAge() const
    {
        return age;
    }
     string getName() const
    {
        return name;
    }
};

class Dog : protected Animal
{
public:
    string setBreed(string n)
    {
        return this->breed = n;
    }
    string getBreed()
    {
        return breed;
    }


private:
    string breed;
};


int main()
{
    int a;
    string n, b;
    Dog D;
    cout << "Enter the name of the Dog: ";
    cin >> n;
    cout << "Enter the age of the Dog: ";
    cin >> a;
    cout << "Enter the breed of the Dog: ";
    cin >> b;
    D.setName(n);//set name is not accesible
    D.setAge(a);
    D.setBreed(b);
    cout << "The name of the animal is: " << D.getName() << endl;
    cout << "The age of the animal is: " << D.getAge() << endl;
    cout << "Breed of the dog: " << D.getBreed() << endl;
}
#包括
#包括
使用名称空间std;
类动物
{
受保护的:
智力年龄;
字符串名;
公众:
无效设置(int a)
{
这个->年龄=a;
}
void setName(字符串n)
{
该->名称=n;
}
int getAge()常量
{
回归年龄;
}
字符串getName()常量
{
返回名称;
}
};
狗类:受保护动物
{
公众:
串接簧片(串n)
{
返回此->品种=n;
}
字符串getbride()
{
回归品种;
}
私人:
弦品种;
};
int main()
{
INTA;
字符串n,b;
狗D;
cout>n;
cout>a;
cout>b;
D.setName(n);//集合名称不可访问
D.设置(a);
D.2(b);

不能使用公共继承而不是受保护的。你想让每个人都知道狗是动物。正如n.m.所说,你使用的继承是错误的。检查并看看你是否能更好地理解这个概念。可能重复我知道我可以使用公共继承访问,但有没有办法使用受保护的继承访问