要计算无效显示的总数,我需要part1marks,part2marks和score的值。因此,我创建了返回函数(这是我根据自己的工作要做的方式)。但是,如下图所示,我得到了不良的输出。
#include<iostream>
using namespace std;
class student
{
int rollno;
public:
void getnumber()
{
cout << "Enter roll number: ";
cin >> rollno;
cout << endl;
}
int putnumber()
{
return rollno;
}
};
class test : virtual public student
{
float part1marks;
float part2marks;
public:
void getmarks()
{
cout << "Enter Marks(Parts 1 and 2): ";
cin >> part1marks >> part2marks;
cout << endl;
}
float putmarks()
{
float marks = part1marks + part2marks;
return marks;
}
};
class sports : virtual public student
{
float score;
public:
void getscore()
{
cout << "Enter score: ";
cin >> score;
cout << endl;
}
float putscore()
{
return score;
}
};
class result : public test, public sports
{
float total;
public:
void display()
{
test t;
sports s;
float sc = s.putscore();
float ms = t.putmarks();
total = sc + ms;
cout <<"Total marks= "<< total;
}
};
int main()
{
result obj;
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
system("pause");
return 0;
}
预期产量
输入卷号:21
输入标记(第1部分和第2部分):22.2 22.2
输入分数:22.2
总标记= 66.6按任意键继续。 。
实际输出
输入卷号:21
输入标记(第1部分和第2部分):22.2 22.2
输入分数:22.2
总标记= -3.22123e + 08按任意键继续。 。
答案 0 :(得分:0)
您正在display()
中使用未初始化的值创建新对象。
void display()
{
test t; // <- This is a new object with uninitialized members variables
sports s; // <- This is a new object with uninitialized members variables
float sc = s.putscore(); // Replace with this->putscore() or simply putscore()
float ms = t.putmarks(); // Replace with this->putmarks() or simply putmarks()
total = sc + ms;
cout <<"Total marks= "<< total;
}
多重继承几乎从来不是一个好主意。您的作业真的强迫您这样做吗?