在派生类中定义自定义返回类型的受保护方法?

时间:2015-04-21 13:47:28

标签: c++ oop inheritance struct protected

使用C ++并尝试编写一个方法,该方法返回类型为thing的实体,该实体在其父类中定义为受保护但收到以下错误:

'thing' does not name a type

class A {
protected:
    struct thing{

    };
};

class B : public A {
    thing getThing();
};

thing B::getThing(){ // Error occurs on this line
    return new thing;
}

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

这里有两个问题。

首先,您必须使thing符合名称空间A

A::thing B::getThing(){ // Error occurs on this line
    return new thing;
}

此外,new thing将返回thing*,但不能隐式转换为thing,因此您需要返回A::thing*或{ {1}}。

答案 1 :(得分:0)

您需要将A::放在getThing上的返回类型前面:

A::thing B::getThing(){
    return thing();
}

thingA命名空间内声明,因此当您不在该命名空间中时,需要指定A。尽管如此,您的代码将无法编译,因为您声明getThing返回thing但现在它返回thing *。您需要将其更改为return thing()或更改声明以返回thing *