![](/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.