如何从子类对象访问超类函数

时间:2020-03-27 04:32:13

标签: c++

是否可以从子类访问超类方法? 我将Apple类作为Fruit类的子类,但是无法从Apple类的对象访问Fruit类中的setName函数。 你能给我什么建议吗?

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

class Fruit {
public:
    Fruit(string str)
    {
        cout << "Fruit class" << endl;
        name = str;
        cout << name << endl;
    }

    void setName(string str) {
        name = str;
    }
private:
    string name;
};

class Apple:Fruit {
public:
    Apple() :Fruit("apple"){
        cout << "Apple class" << endl;

    }
    void setName(string str) {
        name = str;
    }
};

int main()
{
    Apple apple;

    apple.setName("Orange");  //I can not access to setName function from apple
    return 0;
}

4 个答案:

答案 0 :(得分:2)

像这样使用public继承:

class Apple : public Fruit

class的默认可见性为private(如果未指定)。这就是为什么您无法访问基类的public成员的原因,因为它们具有private的可见性,因此它们现在是私有的。

class相反,struct的默认可见性为public,即:

struct Base {};
struct Derived : Base {}; // public inheritance

在您的代码中,派生类中重写的setName()方法是多余的,因为它无法直接操作私有数据成员name。您必须使用基类方法在覆盖的方法中设置name。截至目前,您没有使用该方法做任何其他事情,因此您不需要它。

这是您的工作代码(live):

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

class Fruit {
public:
    Fruit(string str)
    {
        cout << "Fruit class" << endl;
        name = str;
        cout << name << endl;
    }

    void setName(string str) {
        name = str;
    }
private:
    string name;
};

class Apple : public Fruit {       // public inheritance
public:
    Apple() :Fruit("apple"){
        cout << "Apple class" << endl;
    }
    // void setName(string str) {  // Redundant!
    //     name = str;             // `name` is not accessible here!
    // }
};

int main()
{
    Apple apple;
    apple.setName("Orange");      // Accessible here
    return 0;
}

有关更多信息,请参考:
Difference between private, public, and protected inheritance

答案 1 :(得分:0)

您的Apple类使用的是私有继承(未指定继承的 type 时是默认值),因此所有Fruit' public的{​​{1}}方法是private中的Apple,因此main()无法调用。您需要使用 public 继承来解决此问题。

此外,无需在setName()中重新实现Apple。从setName()继承的Fruit只要在Apple中作为公共方法继承就足够了。

class Apple : public Fruit {
public:
    Apple() : Fruit("apple"){
        cout << "Apple class" << endl;
    }
}; 

答案 2 :(得分:0)

使用公共继承

class Apple:public Fruit

在班级默认为私人

class Apple:Fruit

相同
class Apple:private Fruit

您在此处设为私有,因此即使是公开对象,也无法按Apple对象访问Fruit成员。

class Apple:public Fruit
{
public:
    Apple() :Fruit("apple")
    {
        cout << "Apple class" << endl;
    }
};

或者,如果您要像这样私人使用

class Apple:Fruit 
{
public:
    Apple() :Fruit("apple")
    {
        cout << "Apple class" << endl;
    }
    void setName(string str) 
    {
      Fruit::setName(str);
    }
};

答案 3 :(得分:0)

首先,将Apple类别更改为

26.1.8.5 MMC/ SD Cards

然后,使用此方法

class Apple: public Fruit
相关问题