C++ 初始化指针数组
C++ Initializing Array of Pointers
我知道你可以做到这一点:
T * myPtr = 0;
将指针设置为 NULL 值。但是,当我尝试这样做时:
T * myPtrArray[2] = {0, 0};
我收到 "expected expression" 语法错误。为什么?
注意,我使用的是 g++,上面的代码出现在 class 构造函数中:
template <class T>
RBTree<T>::RBTree() {
m_Data = T();
m_Children = {0, 0};
m_Parent = 0;
m_Color = BLACK;
}
有问题的 class 成员声明为:
T m_Data;
RBTree<T> * m_Children[2];
RBTree<T> * m_Parent;
bool m_Color;
从 C++11 开始,您可以使用 nullptr
而不是 0
。首选使用 nullptr
,因为它是一个指针而不是整数。那么,你可以这样做:
T * myPtrArray[2] = {nullptr, nullptr};
无论如何,你的代码在我的编译器上运行良好,你可以看到一个使用 0
和 nullptr
的示例,编译没有错误 on ideone.
形式T * myPtrArray[2] = {0, 0};
被称为aggregate initialization。它在赋值中没有对应项,因此写作
T * myPtrArray[2];
myPtrArray = {0, 0};
无效。
在class构造的情况下,聚合初始化在c++98/03中不可用。
如果你的编译器支持c++11标准,你可以使用统一的初始化语法。在您的示例中有两种初始化 m_Children
的方法:
#1
在构造函数中:
template <class T>
RBTree<T>::RBTree(): m_Children {0, 0} /* other init here */ {
}
#2
在class成员声明期间:
T m_Data;
RBTree<T> * m_Children[2] {0, 0};
RBTree<T> * m_Parent;
bool m_Color;
我知道你可以做到这一点:
T * myPtr = 0;
将指针设置为 NULL 值。但是,当我尝试这样做时:
T * myPtrArray[2] = {0, 0};
我收到 "expected expression" 语法错误。为什么?
注意,我使用的是 g++,上面的代码出现在 class 构造函数中:
template <class T>
RBTree<T>::RBTree() {
m_Data = T();
m_Children = {0, 0};
m_Parent = 0;
m_Color = BLACK;
}
有问题的 class 成员声明为:
T m_Data;
RBTree<T> * m_Children[2];
RBTree<T> * m_Parent;
bool m_Color;
从 C++11 开始,您可以使用 nullptr
而不是 0
。首选使用 nullptr
,因为它是一个指针而不是整数。那么,你可以这样做:
T * myPtrArray[2] = {nullptr, nullptr};
无论如何,你的代码在我的编译器上运行良好,你可以看到一个使用 0
和 nullptr
的示例,编译没有错误 on ideone.
形式T * myPtrArray[2] = {0, 0};
被称为aggregate initialization。它在赋值中没有对应项,因此写作
T * myPtrArray[2];
myPtrArray = {0, 0};
无效。
在class构造的情况下,聚合初始化在c++98/03中不可用。
如果你的编译器支持c++11标准,你可以使用统一的初始化语法。在您的示例中有两种初始化 m_Children
的方法:
#1
在构造函数中:
template <class T>
RBTree<T>::RBTree(): m_Children {0, 0} /* other init here */ {
}
#2
在class成员声明期间:
T m_Data;
RBTree<T> * m_Children[2] {0, 0};
RBTree<T> * m_Parent;
bool m_Color;