java - 无法在 C++ 中编写相同的 Java 代码,因为 "cannot initialize class member here"错误

标签 java c++ linked-list turbo-c++

我正在做单向链表的 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/

相关文章:

c++ - 打印双向链表

java - 在两点之间画一条线

java - 如何使用 WindowBuilder 在 Eclipse Mars 中调整 Tab 键顺序

java - 不生成@XMLRootElement jaxb

java - 谁能告诉我为什么这会返回一个空列表(NPE)?

无法访问 C 中地址处的内存

java - 使用 IBM WAS ConnectionFactory 和 Spring 时出错

c++ - 调用 operator<< 时出现链接器错误,如何解决?

c++ - 从 Windows 卸载时如何从其他用户帐户中删除 ProgID?

c++ - _bstr_t 到 char 指针并调用 atof(...)