【问题标题】:Defining a protected method of custom return type within a derived class?在派生类中定义自定义返回类型的受保护方法?
【发布时间】:2015-04-21 13:47:28
【问题描述】:

使用 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;
}

我怎样才能做到这一点?

【问题讨论】:

  • B::thing B::getThing() {...}

标签: c++ oop inheritance struct protected


【解决方案1】:

这里有两个问题。

首先,您必须将thing 限定在命名空间A 内。

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

另外,new thing 将返回 thing*,它不能隐式转换为 thing,因此您需要返回 A::thing*return thing()

【讨论】:

  • 顺便说一下,命名空间不需要尾随返回类型:auto B::getThing() -> thing*
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 2020-11-11
    • 2021-01-22
    • 2010-09-30
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多