2014-09-03 51 views
0

我在课程中有一个学生数组对象。我如何初始化分配给学生姓名[]的数组大小?我应该使用指针还是数组?如何在类对象内部分配数组

#include <iostream> 
#include "student.h" 
#include "course.h" 

int main(int argc, char** argv) { 

    Student student[4]; 
    Course computerClass(student); 
    return 0; 
} 

#ifndef COURSE_H 
#define COURSE_H 
#include "student.h" 
class Course 
{ 
    private: 
    Student name[]; 
    public: 
     Course(); 
     Course(Student []); 

}; 

#endif 

#include "course.h" 
#include <iostream> 
using namespace std; 
Course::Course() 
{ 
} 

Course::Course(Student []){ 



} 

回答

1

可使用数组只有当你在编译时知道数组大小,使用std::vector当你不:

#include <iostream> 
#include "student.h" 
#include "course.h" 


int main(int argc, char** argv) { 

    Students students(4); 
    Course computerClass(students); 
    return 0; 
} 

#ifndef COURSE_H 
#define COURSE_H 
#include "student.h" 

typedef std::vector<Student> Students; 

class Course 
{ 
    private: 
     Students names; 
    public: 
     Course(); 
     Course(const Students &students); 

}; 

#endif 

#include "course.h" 
#include <iostream> 
using namespace std; 
Course::Course() 
{ 
} 

Course::Course(const Students &students) : names(students) 
{ 
} 
+0

谢谢,但只是想知道你为什么在构造函数中的参数都使用const? – Vanishadow 2014-09-03 22:52:11

相关问题