【发布时间】:2020-08-04 22:31:08
【问题描述】:
我正在尝试完成一项 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(){}
再次感谢任何帮助。即使您不回复,也感谢您的关注。
【问题讨论】:
-
请将错误的确切文本复制到您的问题中。您遇到的问题是 Petr 确定您将动态内存分配给名为
stuCourses的局部变量(然后在构造函数结束时销毁导致内存泄漏),但您也尝试调用非-static 成员函数 (course::printCourse()),然后是不太明显的内存泄漏问题。 (如果您正在管理诸如内存之类的资源,则需要实现适当地处理资源的析构函数、复制构造函数和赋值运算符) -
我刚刚意识到您的
numCourses在您使用它分配内存时未初始化。您需要将其作为参数传递给您的构造函数,或者像使用 name 一样在命令行上请求它。 -
我正在尝试完成一项 C++ 学校作业,但我有一个问题可能很简单。 -- 这并不简单。为什么老师们仍然以这种方式教授 C++?你有
std::vector<course>来解决动态数组的所有这些问题。否则,您只会在尝试实现一个重要的类时感到沮丧。 -
感谢约翰的两个答复。当我重新输入文本时,我不小心忽略了 numCouses 的初始化。正如您所提到的,明显的剩余错误是“非静态成员引用必须相对于特定对象”/“course::printCourse':非静态成员函数的非法调用”
-
printCourse不是静态成员函数。必须在course的实例上调用它。
标签: c++ arrays class dynamic private