在C ++中创建和使用动态数组

问题描述 投票:0回答:1

我正在尝试完成C ++的学校作业,我有一个问题,可能是简单的问题。我从头开始构建了所有文件(超过了下面的数量,这是不必要添加的),而我被抓挠了。有人告诉我创建一个对象的私有动态数组,该数组将由用户输入定义。这将在“ student.cpp”文件中。该动态数组用于创建将操作“ course.cpp”文件的对象。我尝试了一系列变通办法,但没有找到答案,并且期望答案很明显。这是我的代码的精简版。我还评论了该问题在student.cpp文件中的位置以及其他可能出现的问题。

任何建议将不胜感激。我再次手动输入了此内容,因此,如果出现输入错误,请提前道歉。如果我在最初的帖子后发现任何内容,我将进行编辑。

//source.cpp
#include <iostream>
#include "student.h"
using namespace std;
void main() {
    student stu;
    stu.printRecord();
}
//student.h
#ifndef STUDENT_H
#define STUDENT_H
#include<iostream>
#include<string>
#include "course.h"
using namespace std;
class student{
public:
    student();
    void printRecord();
    ~student();
private:
    string name;
    int numCourses;
    course* stuCourses;        //possible source of error
};
#endif
//student.cpp
#include "student.h"
student::student(){
    cout << "enter name: ";
    getline(cin,name);
    cout << "Enter the number of courses the student is taking: ";
    cin >> numCourses;
    course* stuCourses= new course[numCourses];     //possible source of error (now this->stuCourses = new course[numCourses];)
}
void student::printRecord(){
    cout << endl << name << endl;
    course::printCourse();         //Error at this point
}
//course.h
#ifndef COURSE_H
#define COURSE_H
#include <iostream>
using namespace std;

class course{
public:
    course();
    void printCourse();
    ~course();
private:
    string title;
};
#endif
//course.cpp
#include <iostream>
#include "course.h"
course::course(){
    cout << "Title: ";
    cin >> title;
}
void course::printCourse(){
    cout <<title;
}
course::~course(){}

再次感谢您的帮助。即使您没有回应也感谢您的关注。

c++ arrays class dynamic private
1个回答
0
投票

而不是:course * stuCourses =新课程[numCourses];

可以使用:this-> stuCourses =新课程[numCourses];

甚至:stuCourses =新课程[numCourses];

© www.soinside.com 2019 - 2024. All rights reserved.