gpt4 book ai didi

c++ - 如何在派生实例化之前创建抽象类

转载 作者:搜寻专家 更新时间:2023-10-31 01:05:37 24 4
gpt4 key购买 nike

如何创建派生类并在创建派生类时实例化基类。

像这样

template<class T> 
struct Base
{
typedef T type;
static const int n = 3;
virtual int f() = 0;
int f(int x) { return x * 2; }
};

// doesn't compile!
template<class T>
struct Derived : Base<T>
{
type field; // The compiler doesn't know Base<T>::type yet!
int f() { return n; } // the compiler doesn't know n yet, and f(int) is maksed!
};

最佳答案

您可以使用 using 输入相关名称声明:

template<class T> 
struct Base
{
typedef T type;
static const int n = 3;
virtual int f() = 0;
int f(int x) { return x * 2; }
};

template<class T>
struct Derived : Base<T>
{
using typename Base<T>::type;
using Base<T>::n;

type field;
int f() { return n; }
};

Live example

对于以这种方式继承的类型,您还必须使用 typename关键字(就像我上面所做的那样),以便编译器知道该名称指的是一种类型。有一个 question on SO了解有关此要求的更多信息。

另一种方法是显式限定名称:使用 typename Base<T>::type而不是 typeBase<T>::n而不是 n .您选择哪一个主要取决于偏好。

关于c++ - 如何在派生实例化之前创建抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com