使用模板前向声明类

发布于 2024-11-30 01:51:51 字数 324 浏览 5 评论 0原文

我可以对模板类使用前向声明吗?
我尝试:

template<class que_type>
class que;
int main(){
    que<int> mydeque;
    return 0;
}
template<class que_type>
class que {};

我得到:

error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.

Can I use forward declaration for template class?
I try:

template<class que_type>
class que;
int main(){
    que<int> mydeque;
    return 0;
}
template<class que_type>
class que {};

I get:

error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

榕城若虚 2024-12-07 01:51:51

这不是模板问题。除非已完全定义类型,否则不能将其用作按值变量。

This is not a template issue. You cannot use a type as a by-value variable unless it has been fully defined.

习惯成性 2024-12-07 01:51:51

不可以。在实例化时,编译器必须看到类模板的完整定义。对于非模板类也是如此。

No. At the point of instantiation, the complete definition of the class template must be seen by the compiler. And its true for non-template class as well.

兰花执着 2024-12-07 01:51:51

类的前向声明应该指定完整的参数列表。这将使编译器知道它的类型。

当类型被前向声明时,编译器只知道该类型存在;它对其大小、成员或方法一无所知,因此称为不完整类型。因此,您不能使用该类型来声明成员或基类,因为编译器需要知道该类型的布局。

您可以:

1。声明一个成员指针或对不完整类型的引用。
2. 声明接受/返回不完整类型的函数或方法。
3. 定义接受/返回不完整类型的指针/引用的函数或方法。

请注意,在上述所有情况下,编译器不需要知道类型和类型的确切布局。这样编译就可以通过了。

示例 1:

class YourClass;
class MyClass 
{
    YourClass *IncompletePtr;
    YourClass &IncompleteRef;
};

Forward declaration of a class should have complete arguments list specified. This would enable the compiler to know it's type.

When a type is forward declared, all the compiler knows about the type is that it exists; it knows nothing about its size, members, or methods and hence it is called an Incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type.

You can:

1. Declare a member pointer or a reference to the incomplete type.
2. Declare functions or methods which accepts/return incomplete types.
3. Define functions or methods which accepts/return pointers/references to the incomplete type.

Note that, In all the above cases, the compiler does not need to know the exact layout of the type & hence compilation can be passed.

Example of 1:

class YourClass;
class MyClass 
{
    YourClass *IncompletePtr;
    YourClass &IncompleteRef;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文