struct Element{
Element() {}
int data = NULL;
struct Element* right, *left;
};或
struct Element{
Element() {}
int data = NULL;
Element* right, *left;
};我正在处理二叉树,我正在查找一个例子。在这个例子中,Element* right是struct Element* right。它们之间有什么不同,哪一个更适合编写数据结构?
我从这个网站上查到:https://www.geeksforgeeks.org/binary-tree-set-1-introduction/
发布于 2022-05-29 10:18:40
在C++中,定义类还定义了同名的类型,因此使用struct Element或仅使用Element就意味着相同的事情。
// The typedef below is not needed in C++ but in C to not have to use "struct Element":
typedef struct Element Element;
struct Element {
Element* prev;
Element* next;
};您很少需要在C++中使用C++(在定义中除外)。
但是,有一种情况是您确实需要它,那就是您需要消除同名类型和函数之间的歧义:
struct Element {};
void Element() {}
int main() {
Element x; // error, "struct Element" needed
}发布于 2022-05-29 10:12:34
在C中,必须使用struct关键字来声明结构变量,但在C++中,它是可选的(在大多数情况下)。
考虑以下例子:
struct Foo
{
int data;
Foo* temp; // Error in C, struct must be there. Works in C++
};
int main()
{
Foo a; // Error in C, struct must be there. Works in C++
return 0;
}示例2
struct Foo
{
int data;
struct Foo* temp; // Works in both C and C++
};
int main()
{
struct Foo a; // Works in both C and C++
return 0;
}在上面的例子中,temp是一个数据成员,它是指向非const Foo的指针。
此外,我建议使用一些good C++ book来学习C++。
https://stackoverflow.com/questions/72422738
复制相似问题