从类模板实现纯虚函数 - 参数类型

Implementing pure virtual functions from class template - parameter types

本文关键字:函数 参数 类型 实现      更新时间:2023-10-16

我想创建一个抽象类模板,强制所有实例使用纯虚函数实现doStuff函数。

我有以下模板:

template<class T>
class X
{
    public:
        X() {};
        virtual ~X() {};
        virtual X<T>& doStuff(X<T>& x) = 0;
};

还有一个 T= int 的实例:

class Y : public X<int>
{
    public:
        Y();
        virtual ~Y();
        Y& doStuff(Y& x) {
            Y res;
            Y& res2 = res;
            return res2;
        }
};

我收到错误消息:

In member function ‘Y& Y::doStuff(Y&)’: cannot declare variable ‘res’ to be of abstract type ‘Y’ because the following virtual functions are pure within ‘Y’: X<T>& X<T>::doStuff(X<T>&) [with T = int]

如果我将参数的类型更改为doStuff in Y ,一切都很好:

class Y : public X<int>
 {
    public:
        Y();
        virtual ~Y();
        Y& doStuff(X<int>& x) {
            Y res;
            Y& res2 = res;
            return res2;
        }
};

为什么当Y实现 X 时,参数不能是对Y对象的引用?

Y& 的返回值不会创建类似的错误消息。

也许我使用了错误的方法来实现我想要的 - 请随时告诉我。

通过将Y&设置为参数,您可以更改doStuff的签名,因此res是抽象的。

即使Y继承了XX<int>&也不Y&

为什么当 Y

实现 X 时,参数不能是对 Y 对象的引用?

因为您必须给出在基数的纯虚函数中声明的确切签名。

这就是为什么

class Y : public X<int> {
    // ...
    X<int>& doStuff(X<int>& x) override;
};

工程。

请参阅工作现场演示。


更不用说返回对局部变量的引用是未定义的行为。