小编Los*_*kos的帖子

使用指针作为返回类型实现模板化接口的函数 -> 冲突返回类型错误

我目前正在学习 C++ 并且遇到了以下问题:我有一个模板化接口 BaseTemplate,我想在 Child 类中实现它,而无需让子类本身成为模板。示例代码如下:

template <typename T>
class BaseTemplate
{
    public:
        virtual const T get() const = 0;
};

class Child : public BaseTemplate<int*>
{
    public:
        Child(int value) : myInt{value} {};
        virtual const int* get() const override { return &myInt; };

    private:
        int myInt{0};
};

int main()
{
    Child myChild = Child(10);
    std::cout << myChild.get() << "\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC 产生以下错误:

main.cpp|16|error: conflicting return type specified for ‘virtual const int* Child::get() const’
main.cpp|9|note: overridden function is ‘const …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance gcc templates return-type

5
推荐指数
1
解决办法
66
查看次数

标签 统计

c++ ×1

gcc ×1

inheritance ×1

return-type ×1

templates ×1