[英]c++ Class containing vectors of other Classes
我正在尝试制作一个包含“班级大学”的程序,其中包含“班级部门” [vector Departments]的向量。 在公开下的“类部门”内部,我有两个构造函数和一个打印函数。
在我的University.cpp中,我试图创建一个函数,该函数添加一个新的对象Department并将其放入“ University”的向量Departments中。 我相信我做错了,因为我试图在University函数中调用Department()的构造函数,并且收到以下错误消息:
$ g++ University.cpp
/usr/li`enter code here`b/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
/tmp/cc6XExwc.o: In function `University::CreateNewDepartment(std::string, std::string, long)':
University.cpp:(.text+0x7d): undefined reference to `Department::Department(std::string, std::string, long)'
collect2: error: ld returned 1 exit status
类部门具有以下专用变量(长ID,字符串名称,字符串位置,长chairID)。 我是否需要使用set()函数来创建对象,如果是的话,我该如何做呢?
下面的大学
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
#include "Person.h"
#include "Student.h"
#include "Faculty.h"
#include "Department.h"
#include "Course.h"
class University
{
protected:
vector<Department> Departments;
vector<Student> Students;
vector<Course> Courses;
vector<Faculty> Faculties;
public:
University();
~University();
bool CreateNewDepartment(string depName, string depLoc, long depChairId);
下面的University.cpp
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
#include "University.h"
bool University::CreateNewDepartment (string n, string l, long c)
{
if ( (c != 0) && (!validFaculty (c) ))
return false;
Department D (n, l, c);
Departments.push_back (D);
return true;
}
部门
#ifndef DEPARTMENT_H
#define DEPARTMENT_H
#include <string>
#include <iostream>
using namespace std;
class Department
{
friend class University;
protected:
long id;
string name;
string location;
long chairId;
static long nextDepartId;
public:
Department();
Department(string n, string l, long c);
void Print() const;
};
#endif
部门
#include "Department.h"
using namespace std;
#include <string>
long Department::nextDepartId;
Department::Department()
{
id = chairId = 0;
name = location = " ";
}
Department::Department(string n, string l, long c)
{
name = n;
location = l;
chairId = c;
}
void Department::Print() const
{
cout << "Name: " << name << endl;
cout << "Id: " << id << endl;
cout << "Location: " << location << endl;
cout << "Chair id: " << chairId << endl;
}
正如@SteveHolodnak和@MM的评论中所说,这里有两个未定义的参考问题。
Department::Department()
引用 使用g++ main.cpp University.cpp Department.cpp
其中main.cpp
是您的文件以及主要功能)应该可以解决所有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.