前向声明:模板和继承
在编写框架时,我遇到了以下问题: 我有 A 类和 B 类,它们是从 A 类派生的。
类 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*
的未知数。可以写前向声明吗?或者我需要一些不同的东西?
是的,我进行了搜索,发现有很多关于模板声明的帖子,但找不到解决我个人问题的方法。对我来说有点复杂。
感谢您的帮助。
When writing a framework I got following problem:
I have class A
and class B
wchich is derived from class A
.
class A
has a function wchich returns 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*
. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的前瞻性声明不正确。它需要是:
Your forward declaration is incorrect. It needs to be: