使用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;
}
我怎样才能做到这一点?
答案 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();
}
thing
在A
命名空间内声明,因此当您不在该命名空间中时,需要指定A
。尽管如此,您的代码将无法编译,因为您声明getThing
返回thing
但现在它返回thing *
。您需要将其更改为return thing()
或更改声明以返回thing *
。