當我使用時class Derived: public Base<int*>,我認為基類模板是一個成員函式,virtual void foo(const int* a) {}因為在編譯期間顯式實體化。但是,如果我這樣寫,它永遠不會顯示“派生類”。發生了什么?
#include <iostream>
using namespace std;
template<typename T>
class Base
{
public:
virtual void foo(const T a)
{
cout << "Base foo" << endl;
}
};
class Derived : public Base<int*> // But " template<typename T> class Derived : public Base<T> {...} " works fine...
{
public:
virtual void foo(const int* a)
{
cout << "Derived foo" << endl;
}
};
int main()
{
Base<int*>* p = new Derived;
p->foo(0); // "Base foo"
}
uj5u.com熱心網友回復:
請注意,對于const T,本身const是限定的T。然后給定T是int*,引數型別的Base<T>::foo,即,const T將是int * const(常量指向非const int),但不const int *(非const指標為const int)。
你應該Derived::foo改為
virtual void foo(int* const a)
{
cout << "Derived foo" << endl;
}
其他問題: (1)最后不要忘記delete指標p;(2)Base應該有一個virtual解構式。
居住
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391771.html
上一篇:有狀態的C 輸入迭代器后增量問題
