簡體   English   中英

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

[英]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的評論中所說,這里有兩個未定義的參考問題。

  1. 沒有主要功能。
  2. 未定義對Department::Department()引用

使用g++ main.cpp University.cpp Department.cpp其中main.cpp是您的文件以及主要功能)應該可以解決所有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM