【问题标题】:C++ overriding virtual templated methodC++ 覆盖虚拟模板化方法
【发布时间】:2019-05-27 03:39:31
【问题描述】:

我正在尝试覆盖 C++ 中的虚函数。在我覆盖该函数后,它实际上并没有覆盖它,因此使类抽象。 下面的代码将使您对问题有一个很好的理解。

正如您在下面看到的,该代码适用于非指针模板(如 int),但因 int 指针而失败。

我想可能是因为指针引用有问题,所以我在 Derived2 的实现中去掉了 & ,但这并没有解决它。

template<class T>
class Base {
    virtual void doSomething(const T& t) = 0;
};
class Derived1: public Base<int>{
    void doSomething(const int& t) {
    } // works perfectly
};
class Derived2: public Base<int*>{ 
    void doSomething(const int*& t) { 
    }
// apparently parent class function doSomething is still unimplemented, making Derived2 abstract???
};

int main(){
    Derived1 d1;
    Derived2 d2; // does not compile, "variable type 'Derived2' is an abstract class"
}

【问题讨论】:

    标签: c++ templates inheritance polymorphism overriding


    【解决方案1】:

    注意,对于参数类型const T&amp;const 是在T 本身上限定的,那么当T 是像int * 这样的指针时,const 应该在指针本身上限定(即int* const),而不是指针(即const int*)。

    正确的类型应该是

    void doSomething(int* const & t)
    

    BTW:您可以使用关键字override 来确认virtual 函数是否被正确覆盖。

    BTW2:将const T&amp; 的样式更改为T const&amp; 可能会更清晰。

    LIVE

    【讨论】:

    • 哦,好吧,这很有意义。谢谢!澄清一下: int a = 3;常量 int* p1 = &b; int* const p2= &b.在这种情况下,p1 的类型意味着 a 的数据值是常数,而 p2 意味着指针 p2 是常数。这是正确的吗?
    • @akarshkumar0101 是的,没错。换句话说,你不能做*p = 42;p2 = nullptr,但可以p = nullptr;*p2 = 42;
    猜你喜欢
    • 2012-11-28
    • 2011-05-21
    • 1970-01-01
    • 2013-01-15
    • 2016-09-28
    • 2011-12-19
    • 2018-01-28
    • 1970-01-01
    相关资源
    最近更新 更多