Los*_*kos 5 c++ inheritance gcc templates return-type
我目前正在学习 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 T BaseTemplate<T>::get() const [with T = int*]’
Run Code Online (Sandbox Code Playgroud)
我清楚地知道错误与此有关,
virtual const int* get() const override { return &myInt; };但我不明白问题出在哪里。如果我将返回类型(当然在两个类中)更改为int,即返回一个值而不是一个指针,它工作正常。那么这里的指针有什么问题呢?
也许它有帮助:在我的实际代码中,我想返回一个指向自定义接口而不是 int 的指针,我相信那里的错误是相关的
file_trees.h|19|error: invalid covariant return type for ‘virtual const IDirectoryNode* FileTree::DepthFirstIterator::getCurrent() const’
iterator_interface.h|10|note: overridden function is ‘const T IIterator<T>::getCurrent() const [with T = IDirectoryNode*]’
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |