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

标签 c++ templates types covariance virtual-functions

我想创建一个抽象类模板,强制所有实例实现 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]

如果我将参数类型更改为 doStuffY ,一切都很好:

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

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

Y&的返回值不会产生类似的错误消息。

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

最佳答案

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

X<int>&不是 Y&尽管Y继承X .

关于c++ - 从类模板实现纯虚函数 - 参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42187597/

相关文章:

c++ - 将变量传递给函数

c++ - 比较 2 个字符串映射的通用 C++ 规则引擎

c++ - 模板类成员函数的参数

c++ - 模板函数的前向声明

c++ - 使用 SFINAE 检测模板方法

types - Elasticsearch:有没有办法将对象字段的所有(可能是动态的)子字段声明为字符串?

c++ - Qt中线程间通信的实现

postgresql - 在 PostgreSQL 中转换为用户定义的数据类型

c# - 在没有基础字典结构的 PowerShell 中使用 C# ExpandoObjects(动态)

c++ - 一个类 C++ (Arduino) 中的多个头文件