簡體   English   中英

如何重寫模板化子類中的非模板化方法

[英]How to override a non-templated method in a templated subclass

#include <iostream>

using namespace std;

class A{
public:
    virtual int foo() const = 0;
};

template <typename T = int>
class B : public A{
public:
    virtual int foo() const override;
};

int B::foo(){ return 3; }

int main(){
    B<int> b;
    cout << "b.foo()=" << b.foo() << endl;
}

而且我收到clang ++的以下錯誤:

clang++ -std=c++11 template_override.cpp
template_override.cpp:16:5: error: expected a class or namespace
int B::foo(){ return 3; }
    ^
1 error generated.

我的問題是,如何在似乎無法使用模板參數的類B中實現方法foo()

我試過將B::foo()變成B<>::foo()但這也不起作用。

您的foo定義缺少const ,並且不是模板:

   template <typename T>
// ^^^^^^^^^^^^^^^^^^^^^
   int B<T>::foo() const { return 3; }
//      ^^^       ^^^^^^

現場演示

記住, B不是一個班級。 B是類模板。

B<T> (對於某些T )是一類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM