【问题标题】:Forward declarations: templates and inheritance前向声明:模板和继承
【发布时间】:2011-05-07 18:11:12
【问题描述】:

在编写框架时,我遇到了以下问题: 我有class Aclass B wchich 派生自class A

class A 有一个返回 B* 的函数。

当然不难:

#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
}

但是我不得不使用像这里这样的模板:

#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();
}

查看代码。如您所见,我不知道如何处理 A B* 的未知数。是否可以编写前向声明?还是我需要一些不同的东西?

是的,我进行了搜索,发现有很多关于模板声明的帖子,但找不到解决我个人问题的方法。对我来说有点复杂。

感谢您的帮助。

【问题讨论】:

    标签: c++ templates inheritance declaration


    【解决方案1】:

    您的前向声明不正确。它必须是:

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

    【讨论】:

    • 谢谢 :) 它适用于这个简单的示例。但我仍然想知道为什么它在我的框架中不起作用。如果我搜索原因,我会写。
    • 好的,我知道我做错了什么 - 编译器开始显示“B 不是模板类型”而不是“B 不是模板” .这是主要问题。这是因为在一个文件中有class B 声明(旧文件我忘记重新制作以使用模板)。这就是为什么我不能声明:template &lt;class Number&gt; B(编译器知道“未模板化”B,所以它不允许我进行新的声明)。正因为如此,我认为没有参数列表的声明是错误的,但它是正确的。再次感谢:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多