"pointer name"未命名类型错误



我是C++的新手。我在标记为//this shows error但它的替代语句(标记为but this works(上得到错误。有人能解释一下吗?

#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
Node *next;
int data;
};
class Que
{
public:
//this shows error
/* 
Node *front, *rear;
front = NULL;
rear = NULL;
*/
//but this works
Node *front = NULL, *rear = NULL;
};

这些:

front = NULL;
rear = NULL;

是赋值语句。这个:

Node *front = NULL, *rear = NULL;

是一个使用类内初始值设定项的声明(定义、初始化(语句。

赋值语句不允许出现在类声明体中,而初始化语句则允许。

您需要一个函数或类构造函数来初始化类对象:

class Node
{
public:
Node *next;
int data;
};
class Que
{
public:
Que() {
Node *front, *rear;
front = NULL;
rear = NULL;
}
};

在前面提到的代码中,frontrear现在有了一个存储类,因为它们在构造函数中,它的作用就像一个函数。


为了更好地澄清,您可以使用以下代码:

class test {
public:
int x;    // declaring a variable outside of a constructor or function
x = 10;   // initialization is not allowed here
}
#define NULL nullptr
class Node
{
public:
Node* next;
int data;
};
class Que1 {
public: //Method 1 - initializer list
Node* front{ NULL }, * rear{ NULL };
};
class Que2 {
public: //Method 2 - assignment operator for initialization
Node* front = NULL, * rear = NULL;
};
class Que3 {
public: //Method 3 - initializer list at constructor
Node* front, * rear;
Que3() : front{ NULL }, rear{ NULL }
{}
};
class Que4 {
public: //Method 4 - assignment after member intialization/construction
Node* front, * rear;
Que4()
{
front = NULL;
rear = NULL;
}
};

你的作业不在函数体上。由于您尝试初始化,我考虑显示不同的语法。方法1是最优选的方法。

相关内容

最新更新