简体   繁体   English

前向声明:模板和继承

[英]Forward declarations: templates and inheritance

When writing a framework I got following problem: I have class A and class B wchich is derived from class A . 在编写框架时,我遇到了以下问题:我有class A class B类是从class A派生出来class A

class A has a function wchich returns B* . class A具有返回B*的函数。

Of course, it's not difficult: 当然,这并不困难:

#include <iostream>
using namespace std;

class B; // forward declaration

class A
{
    public:
        B* ReturnSomeData();
};

class B : public A
{
};

// Implementation:

B* A::ReturnSomeData()
{
    return new B; // doesn't matter how the function makes pointer
}

int main()
{
    A sth;

    cout << sth.ReturnSomeData(); // print adress
}

However I had to use templates like here: 但是我不得不使用像这样的模板:

#include <iostream>
using namespace std;

// This "forward declaration":

template <class Number>
class B<Number>;

// cannot be compiled:
// "7 error: 'B' is not a template"

template <class Number>
class A
{
    public:
        B<Number>* ReturnSomeData();
};

template <class Number>
class B : public A<Number>
{
};

// Implementation:

template <class Number>
B<Number>* A<Number>::ReturnSomeData()
{
    return new B<Number>;
}

int main()
{
    A<int> sth;

    cout << sth.ReturnSomeData();
}

Look at the code. 看看代码。 As you can see I don't know how to deal with unknown by A B* . 正如你所看到的,我不知道如何用A B*处理未知B* Is it possible to write forward declaration? 是否有可能写出前瞻性声明? Or I need something different? 或者我需要不同的东西?

Yes, I searched and I see there are many posts about template declarations but can't find solve for my individual problem. 是的,我搜索过,我看到有很多关于模板声明的帖子,但找不到解决我个人问题的帖子。 It's a bit complex for me. 这对我来说有点复杂。

Thanks for help. 感谢帮助。

Your forward declaration is incorrect. 您的前瞻性声明不正确。 It needs to be: 它需要是:

template <class Number>
class B;
       ^ no argument list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM