我正在做单向链表的 C++ 实现,我已经用 Java 完成了。我的 Java 代码部分如下:
class Node
{
int info;
Node next;
Node()
{
next=null;
}
}
class Op
{
Node front= null;
void display()
{
Node rear=front;
if(rear==null)
System.out.println("List is empty");
else
{
while(rear!=null)
{
System.out.print("["+rear.info+"|"+rear.next+"]"+"--->");
rear=rear.next;
}
System.out.println();
}
}
}
next存放链表中下一个Node的地址,
front指向链表的第一个节点,
rear 用于顺序遍历列表。
下面是我要实现的 C++ 代码:
class Node
{
public:
int info;
Node *next;
Node()
{
next = NULL;
}
};
class Op
{
public:
Node *front = NULL; //error line.
};
int main()
{
return 0;
}
我正在使用 Turbo C++ 3.0 编译器,它给出的错误是:
Cannot initialize a class member here
我知道如果我使用 C++11 可以解决上述问题,但不幸的是代码必须在 Turbo C++ 3.0 中。 front 必须是 NULL 才能检查列表 id 是否为空。 我该如何解决这个问题?
最佳答案
试试这个:-
Class Op
{
public : Node *front;
Op():front(NULL){};
};
void main()
{
Op o // constructor called.
Op *op; // pointer - no constructor called.
Op *op2 = new Op; // constructor called.
cout << o.front; // NULL
cout << op->front; // garbage value
cout << op2->front; // NULL
}
关于java - 无法在 C++ 中编写相同的 Java 代码,因为 "cannot initialize class member here"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27216506/