![](/img/trans.png)
[英]Is it possible to pass a type and a pointer of that type to a c++ template class using a single parameter of a template class?
[英]c++ template Incomplete type using pointer of class inside template
我正在尝试创建一个网格,据我所知,问题来自于在其自身内部使用模板类的指针,这是合法的,直到我尝试用它来做事情就是编译器抱怨的时候。 我正在寻找一种方法来将指针用于其自身内部的一个模板类,以便在使用指针时使用,并在以后执行操作。 我使用g ++版本5编译我使用的编译命令是g ++ * .cpp -o main -std = c ++ 11我得到的错误将遵循代码的代码片段。
struct Vector2D
{
Vector2D( ) { }
Vector2D( int x , int y ): x( x ) , y( y ) { } ;
int x , y ;
} ;
template <typename A>
class GridNode2D ;
template <typename T>
class GridNode2D
{
public:
GridNode2D( ) { } ;
T data ;
Vector2D coOrdinate ;
GridNode2D<T>* left, right, up, down ;
} ;
template <typename T>
class Grid2D
{
public:
Grid2D( ) ;
GridNode2D<T>* head ;
} ;
template <typename T>
Grid2D<T>::Grid2D( )
{
this->head = new GridNode2D<T> ;
this->head->right = new GridNode2D<T> ;
} ;
错误:
main.cpp: In instantiation of ‘class GridNode2D<bool>’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',39)">main.cpp:39:16</span>: required from ‘Grid2D<T>::Grid2D() [with T = bool]’
<span class="error_line" onclick="ide.gotoLine('main.cpp',47)">main.cpp:47:18</span>: required from here
main.cpp:22:26: error: ‘GridNode2D::right’ has incomplete type
GridNode2D<T>* left, right, up, down ;
^
main.cpp:15:7: note: definition of ‘class GridNode2D’ is not complete until the closing brace
class GridNode2D
^
main.cpp:22:33: error: ‘GridNode2D::up’ has incomplete type
GridNode2D<T>* left, right, up, down ;
^
main.cpp:15:7: note: definition of ‘class GridNode2D’ is not complete until the closing brace
class GridNode2D
^
main.cpp:22:37: error: ‘GridNode2D::down’ has incomplete type
GridNode2D<T>* left, right, up, down ;
^
main.cpp:15:7: note: definition of ‘class GridNode2D’ is not complete until the closing brace
class GridNode2D
星号*
在声明中的位置
GridNode2D<T>* left, right, up, down ;
是误导。 “标准”C声明方式会更清楚:
GridNode2D<T> *left, right, up, down ;
在上面更清楚的是,星号属于left
声明,这就是你遇到的问题:你只将left
声明为指针,而不是其他变量。
由于其他变量不是指针,因此您需要GridNode2D<T>
的完整定义才能定义该类的实例,但这是不可能的,因为这些对象是GridNode2D<T>
本身的一部分。 这会导致你得到的错误。
在声明中的所有变量上使用星号,或者为了更好的可读性,将声明拆分为多行:
GridNode2D<T>* left;
GridNode2D<T>* right;
GridNode2D<T>* up;
GridNode2D<T>* down;
声明
GridNode2D<T>* left, right, up, down ;
创建1个指针和3个实例。 将其更改为
GridNode2D<T>* left, *right, *up, *down;
甚至
GridNode2D<T>* left = nullptr;
GridNode2D<T>* right = nullptr;
GridNode2D<T>* up = nullptr;
GridNode2D<T>* down = nullptr;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.