【发布时间】:2011-12-10 14:06:35
【问题描述】:
我创建了一个类数组st[5]。并尝试使用函数显示st[5] 的数据。但它不起作用。
仅显示第一类 (st[0]),并显示“调试错误消息”。不知道是什么问题。
main 函数位于底部。
#include <iostream>
using namespace std;
#define MAX 5 //size of array
//Class 'Student'
class Student
{
public:
int num;
char name[10];
};
//Class 'Lscore' extends Student (virtual)
class Lscore : virtual public Student
{
public:
int eng;
};
//Class 'Nscore' extends Student (virtual)
class Nscore : virtual public Student
{
public:
int math;
};
//Class 'Totscore' extends Lscore, Nscore
class Totscore : public Lscore, public Nscore
{
public:
Totscore(); //Constructor1
Totscore(char name[], int num, int eng, int math); //Constructor2
void Display(); //Print Myself
};
//Constructor1
Totscore::Totscore( )
{
}
//Constructor2
Totscore::Totscore(char name[10], int num, int eng, int math)
{
strcpy_s(this->name, 10, name);
this->num = num;
this->eng = eng;
this->math = math;
}
//Print Myself
void Totscore::Display(){
cout<<this->num<<" "<<this->name<<" ";
cout<<this->eng<<" "<<this->math<<" "<<endl;
}
//Print Array (--- Problem Part !! ---)
void PrintArray(Totscore *stu){
for(int i=0; i< MAX; i++){
stu[i].Display();
}
}
//Main Function
int main(){
Totscore *st[MAX]; //Class Array 'st'
st[0] = new Totscore("A",101,85,77);
st[1] = new Totscore("B",102,90,89);
st[2] = new Totscore("C",103,80,55);
st[3] = new Totscore("D",104,75,85);
st[4] = new Totscore("E",105,85,85);
PrintArray(*st);
}
然后运行屏幕如下。 (我的名声很低,无法上传图片。)
101 A 85 77
并显示“调试错误消息”...
【问题讨论】:
-
令人惊讶的是,在 MacOS X 下使用
g++编译时,您的代码只需进行非常小的修改即可工作。我切换到使用strncpy(this->name, name, 10);,并且代码打印了五行非常好。 -
当我回答你的问题时,你删除了它。所以我无法发布答案,所以我永久丢弃它。现在,问题再次出现,我将不得不再次输入所有内容。对于一个简单的问题,这将是双重工作(所以我没有,特别是因为无论如何都有正确的答案)。以后请不要这样做!
-
@ CygnusX1 。好的我明白了。对此感到抱歉。我是第一次在'StackOverflow',所以我不知道如何正确使用。对不起。