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

时间:2016-02-28 07:22:00

标签: 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)
    {
        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;
}

我想访问set name并使用派生类对象从基类获取名称,因为我正在实现代码无法编译的受保护继承。那么,如何在不使用公共继承和使用派生类对象的情况下使用setter和getter?

0 个答案:

没有答案