简体   繁体   English

在C ++中使用数组作为成员变量初始化类时出错

[英]Errors when initializing class with an array as a member variable in C++

I'm just starting to learn C++ and can't figure out what I'm doing wrong. 我刚刚开始学习C ++,无法弄清楚我在做什么错。

I'm trying to build a class "Holder" that holds an array of up to 100 of another class "Obj". 我正在尝试建立一个类“ Holder”,其中包含最多100个其他类“ Obj”的数组。 I have the following two classes: 我有以下两节课:

class Obj {
public:
    Obj(int k, char v): key(k), val(v) {};
private:
    int key;
    char val;

   friend class Holder;
};


class Holder {
private:
    enum {MAX_SIZE = 100};
    Obj p[MAX_SIZE];
    int pSize = 0;
public:
    Holder();
    ~Holder();
//...
};

When initializing the class Holder from main(), as follows... 从main()初始化类Holder时,如下所示...

int main() {
    Holder test;

    return 0;
}

I'm receiving these errors after running the program: 运行程序后,我收到这些错误:

undefined reference to "Holder::Holder()" and undefined reference to "Holder::~Holder()" 未定义对“ Holder :: Holder()”的引用和未定义对“ Holder ::〜Holder()”的引用

I can't tell if I'm correctly using an array as a class member variable in "Holder"? 我无法确定我是否正确地将数组用作“ Holder”中的类成员变量? Or if I'm missing something in the constructor? 或者,如果我在构造函数中缺少某些内容?

Try this code snippet. 试试这个代码片段。 Since constructor of Holder will require auto initialization of an Obj array, a default constructor is used : 由于Holder的构造函数将需要自动初始化Obj数组,因此使用默认的构造函数:

class Obj {
public:
    Obj() :key(0),val(0){};   //Additional - default constructor
    Obj(int k, char v): key(k), val(v) {};
private:
    int key;
    char val;

   friend class Holder;
};


class Holder {
private:
    enum {MAX_SIZE = 100};
    Obj p[MAX_SIZE];
    int pSize = 0;
public:
    Holder(){}   // constructor definition 
    ~Holder(){}   // destructor definition 
//...
};

int main()
{
    Holder test;
}

Consider using std::array (or std::vector) and perhaps also std::pair instead of Obj. 考虑使用std :: array(或std :: vector),也可能使用std :: pair代替Obj。

std::array<std::pair<int, char>, 100> p;  // Will automatically init with zeroes
// Example of using it:
p[50] = std::make_pair(1234, 'a');
std::cout << "key:" << p[50].first << ", val:" << p[50].second << std::endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM