【问题标题】:Trouble with nested classes. "error: expected unqualified-id before '{' token"嵌套类的问题。 “错误:'{'令牌之前的预期不合格ID”
【发布时间】:2014-04-07 06:57:50
【问题描述】:

我在声明嵌套类时遇到问题。我的问题是如何正确声明嵌套类并调用其成员。我试过用谷歌搜索它并尝试了不同的方法,但我似乎无法让它工作。现在我在 LongInt::Digit{

这就是我正在尝试的:

头文件

class LongInt {

 public:
    class Digit{
        public:
        int data;
        Digit(int d);
    };

    // Constructor
    LongInt();
};

Cpp 文件

#include <iostream> 
#include "LongInt.h"
using namespace std;

LongInt::Digit{
    Digit next;
    Digit prev;

    LongInt::Digit::Digit (int d) { 
         data = d;
         next = NULL;
         prev = NULL;
    }
}

LongInt::Digit front;
LongInt::Digit back;
LongInt::Digit curr;

LongInt::LongInt() {
    front = NULL;
    back = NULL;
    curr = NULL;
}

【问题讨论】:

  • 看来你忘了关闭LongInt class
  • 对不起,它在我的代码中。我忘了把它复制到问题中。
  • 还是少了一个分号};
  • 那里也有。对不起,我无法正确复制。包括警卫和其他所有东西也都在那里。
  • .cpp 文件中的第一个代码块在语法上是错误的。你想做什么?

标签: c++ class nested-class


【解决方案1】:

这个

LongInt::Digit{
    Digit next;
    Digit prev;

    LongInt::Digit::Digit (int d) { 
        data = d;
        next = NULL;
        prev = NULL;
    }
};

看起来您正在对Digit 类进行“部分重新声明”,这是不可能的。

您应该在标题中完全声明您的嵌套类

class LongInt {

 public:
    class Digit{
        public:
        int data;
        Digit(int d);
        Digit* next;
        Digit* prev;
    };

    // Constructor
    LongInt();
};

你的构造函数就像

LongInt::Digit::Digit (int d) : data(d), next(NULL), prev(NULL) {
}

【讨论】:

  • +1 用于初始化列表。我在回答中跳过了它,以尽量保留他的代码。
【解决方案2】:

内部类的成员应该在内部类中声明。 另外,我认为有几个地方你打算有指针,但你有对象(你通常想将 NULL 分配给指针)。

另外,您只声明了一个带有 intDigit 构造函数,而没有声明不带参数的构造函数,因此您不能在没有参数的情况下声明 Digit

最后,你真的不应该在LongInt::LongInt() 中做三个赋值,因为那些变量不是指针。

这是.h 文件:

class LongInt {

 public:
    class Digit{
        public:
            Digit*  next;
            Digit*  prev;
            int data;
            Digit(int d);
    };

    // Constructor
    LongInt();
};

这是.cc 文件:

#include <iostream> 
#include "LongInt.h"
using namespace std;

LongInt::Digit::Digit (int d) { 
     data = d;
     next = NULL;
     prev = NULL;
}

LongInt::Digit front(1);
LongInt::Digit back(1);
LongInt::Digit curr(1);

LongInt::LongInt() {
    // front = NULL;
    // back = NULL;
    // curr = NULL;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多