如何在类对象中分配数组

时间:2014-09-03 22:30:27

标签: c++ arrays object

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

#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 个答案:

答案 0 :(得分: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 ) 
{
}