结构错误的构造函数(调用类的构造函数 denconstructor,用于填充结构)

Constructor of structure error (calling constructor denconstructor of class, which fill the structure)

本文关键字:结构 构造函数 用于 填充 调用 错误 denconstructor      更新时间:2023-10-16

我有以下结构:

template <class T>
struct Array{
    int lenght;
    T * M;
    Array( int size ) : lenght(size), M(new T[size])
    {
    }
    ~Array()
    {
       delete[] M;
    }
};

和类(将填充结构的对象):

class Student{
private:
int ID;
int group;
char name[];
 public:
     Student();
     ~Student();
    void setStudent(int,int,char){
    }
    char getName(){
        return *name;
    }
    void getGroup(){
    }
    void getID(){
    }
};

现在,当我想初始化数组类型时,我在 Main.cpp 中得到以下内容:

#include <iostream>
#include "Domain.h"
#include "Student.h"
//#include ""
using namespace std;
int main(){
    cout<<"start:"<<endl<<endl;
    Array <Student> DB(50);
    Array <Student> BU(50);

    return 0;
}

错误:

g++ -o Lab6-8.exe UI.o Repository.o Main.o Domain.o Controller.o
Main.o: In function `Array':
D:c++BeginLab6-8Debug/..//Domain.h:16: undefined reference to `Student::Student()'
D:c++BeginLab6-8Debug/..//Domain.h:16: undefined reference to `Student::~Student()'
Main.o: In function `~Array':
D:c++BeginLab6-8Debug/..//Domain.h:21: undefined reference to `Student::~Student()'

知道为什么吗?

当你写:

class Student
{
public:
   Student();
   ~Student();
};

您已经显式声明了类构造函数和析构函数,因此编译器没有为您定义它们 - 您需要提供它们的定义(实现)。在微不足道的情况下,这将完成这项工作:

class Student
{
public:
   Student(){};
   ~Student(){};
};

这是因为您已经声明Student的构造函数和析构函数,但缺少它们的定义

您可以在 Student 声明中内联提供这些定义,大概在 .h 文件中:

Student() {
    // initialize the student
}
~Student() {
    // release dynamically allocated parts of the student
}

或在 CPP 文件中的类声明之外:

Student::Student() {
    // initialize the student
}
Student::~Student() {
    // release dynamically allocated parts of the student
}

作为旁注,name可能应该是std::string,而不是char,除非你真的想要一个字母的名字。