STRUCT考虑到一段代码:C++:指针在结构定义问题
struct myStruct
{
myStruct *next;
};
接下来是在结构中定义声明结构的指针,是吗?
什么是 - 下一个 - 的实用程序?我如何使用它?
STRUCT考虑到一段代码:C++:指针在结构定义问题
struct myStruct
{
myStruct *next;
};
接下来是在结构中定义声明结构的指针,是吗?
什么是 - 下一个 - 的实用程序?我如何使用它?
好像它是链接列表的实现。
不是一个实现,而是数据结构。 –
该指针的用途是您在myStruct
中执行的任何操作。您可以使用此指针与其他myStruct
结构体(通过指针)保持直接关系,并直接操纵它们(即像“知道”其他对象一样)。
例如(请注意,所有意图和目的,结构在C++是公共类),
class Test
{
public:
doSomethingToTheOtherStruct() {
if(t != NULL)
t->touch();
setTouched(bool touch) {
touched = touch;
}
setT(Test* other) {
t = other;
}
bool isTouched() const {
return touched;
}
private:
Test* t;
bool touched;
};
这个类有一些非常简单的方法,如果能够证明使用指针的力量。下面是一个使用它的例子。
#include <iostream>
using namespace std;
int main()
{
Test t1;
Test t2;
Test* t3 = new Test;
// Notice that we set the pointers of each struct to point to a different one
// This is not necessary, but is definitely more useful than setting it to itself
// since you already have the "this" pointer in a class.
t1->setT(&t2);
t2->setT(t3);
t3->setT(&t1);
cout<< t1.isTouched() << t2.isTouched() << t3->isTouched() << endl;
t1->doSomethingToTheOtherStruct();
t2.doSomethingToTheOtherStruct();
cout<< t1.isTouched() << t2.isTouched() << t3->isTouched() << endl;
delete t3;
return 0;
}
请注意此代码的结果。 t1
从未设置为触摸,但无意中(通过指针),t2
和t3
变得“感动”。
如果您想将这些结构链接在一起以便稍后遍历它们,您可以使用next。当然,让myStruct中的其他成员更有意义。
例如:
struct myStruct
{
int data;
myStruct *next;
};
myStruct st_1;
myStruct st_2;
st_1.data = 1;
st_2.data = 2;
st_1.next = &st_2; //st_1.next->data is now 2
这是正确的。这种嵌套结构用于linked lists。
事实上,它是一个指向同一类的指针,并且成员变量名为“next”,这表明它是一个链表,正如其他人指出的那样。
如果变量是一个指向同一个类的指针,但被称为“父”,它很可能是某种父/子关系。 (例如,具有也是小部件的父级的GUI小部件)。
你可能会质疑究竟是为什么你被允许这样做:答案是指向数据-types都是一样的大小,所以编译器将已经知道它有多少字节需要这个指针。
出于同样的原因,您可以在您的类(或结构体)中指向仅为其声明和未定义数据类型的类型。 (很常见)。
这看起来像一个单独链接列表。 –
由于您将问题标记为C++,因此我想指出,除了可能出于教育目的,您可能不需要自己创建(单独)链接列表。您可以使用'std :: list'类模板为您执行杂耍指针的繁重工作 - 只需将适合于将有效内容建模到模板的类型即可。 –
但他可能是一名学生,需要学习数据结构。您不使用标准库学习数据结构,而是为了教育目的而编写它们。 在生产代码中,我会希望看到人们使用标准库,除非他们有一个非常好的理由不要。 – CashCow