结构错误的构造函数(调用类的构造函数 denconstructor,用于填充结构)
Constructor of structure error (calling constructor denconstructor of class, which fill the structure)
我有以下结构:
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
,除非你真的想要一个字母的名字。
相关文章:
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 嵌套的模板结构构造函数实现
- 其他结构中的结构构造函数
- CPP/C 中的常量用法和结构构造函数中的澄清
- 聚合结构构造函数
- 结构构造函数调用不明确
- 关于结构构造函数和析构函数行为-C++
- 带有指针的C++结构:构造函数和析构函数
- 结构构造函数导致堆栈溢出的问题
- C++结构构造函数和函数冲突
- 嵌套结构构造函数和并集的问题
- C++结构构造函数
- 调用结构构造函数后初始化的值是什么
- 在结构构造函数中使用"this"关键字编译错误?-C++
- 这可能吗?在 C# 中调用托管 c++ 结构构造函数
- C++ - 结构构造函数,尝试取消指向结构的指针时出现重定义错误
- C++结构构造函数错误
- 结构构造函数语法
- 结构构造函数错误,为什么使用默认构造函数会调用错误
- Qt 将 QString 传递给结构构造函数不起作用