包含其他类向量的c ++类

时间:2017-11-21 04:02:07

标签: c++ oop

我正在努力制作一个拥有" Class University"包含"类部门"的矢量; [矢量部门]。在"类部门内部#34;在公共场合我有两个构造函数和一个打印函数。

在我的University.cpp中,我正在尝试创建一个添加新对象Department的函数,并将其放入" 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

Class Departments具有以下私有变量(long id,string name,string location,long chairID)。我是否需要使用set()函数来创建对象,如果是这样,我将如何进行此操作?

下面的University.h

#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;
}

Department.h

#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

Department.cpp

#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;
}

1 个答案:

答案 0 :(得分:0)

正如@SteveHolodnak和@ M.M.的评论中所述,这里有两个未定义的引用问题。

  1. 没有主要功能。
  2. Department::Department()
  3. 的未定义引用

    使用g++ main.cpp University.cpp Department.cpp其中main.cpp是您的主要功能的文件应解决您的所有问题。