【问题标题】:Unable to write the same Java code in C++ because "cannot initialize class member here" ERROR无法在 C++ 中编写相同的 Java 代码,因为“无法在此处初始化类成员”错误
【发布时间】:2015-01-28 18:09:48
【问题描述】:

我正在做一个我已经在 J​​ava 中完成的单链表的 C++ 实现。我的 Java 代码的 Fraction 如下:

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 编译器,它给出的错误是:

这里不能初始化类成员

我知道如果我使用 C++11 可以解决上述问题,但不幸的是代码必须在 Turbo C++ 3.0 中。 front 必须为 NULL 以检查列表 id 是否为空。 我该如何解决这个问题?

【问题讨论】:

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


【解决方案1】:

试试这个:-

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
}

【讨论】:

  • 我在 main() 中试过这个:Op *op; coutfront;
  • 并且返回了一个地址而不是空值,我如何在 if() 条件中检查它是否为空?
  • 我复制粘贴了你的代码,所有三个 cout 语句的输出都是:0x8f850000
  • 垃圾值和空值一样吗?
【解决方案2】:

在构造函数中初始化它:

Op() :
 front(NULL);
{}

有趣的是,它在 Turbo C++ 中不起作用。 g++ 可以处理。

【讨论】:

    【解决方案3】:

    这是在 C++ 中执行此操作的一种方法:

    class Op
    {
    public:
        Node *front;
        Op() : front(NULL) {}  // default constructor
    };
    

    【讨论】:

    • 我尝试在 main() 中访问 front,它显示了一个地址。这应该返回地址而不是 NULL 值吗?
    • 如果列表为空,则 front 必须包含 NULL 但它里面有一些地址。 if() 条件会失败吗?
    【解决方案4】:

    你有调用头文件吗? 有时 JAVA 程序员忘记在 C++ 中包含头文件。 :-P

    我认为这条线:-

    public * front = NULL;
    

    应该是:-

    public : NODE *front = NULL;
    

    【讨论】:

    • 这是一个错字,我的错。这不是问题
    • 是的,我已经调用了所有需要的头文件
    猜你喜欢
    • 2016-08-02
    • 2012-06-30
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多