class student
{
private:
int admno;
char sname[20];
class Student_Marks
{
private:
float eng, math, science, computer, Hindi;
float total;
public:
void sMARKS()
{
cin >> eng >> math >> science >> computer >> Hindi;
}
float cTotal()
{
total = eng + math + science + computer + Hindi;
return total;
}
};
public:
void showData()
{
cout << "\n\nAdmission Number :" << admno;
cout << "\nStudent Name :" << sname;
cout << "\nTotal Marks :" << cTotal();
}
};
我想在外部类函数cTotal()
中调用内部类函数showData()
。
在访问外部类中的内部类函数时出现错误。
答案 0 :(得分:0)
只要将其称为“嵌套类”而不是内部类,您就可以在语言指南中找到适当的引用。这只是封闭类范围内的类型定义,您必须创建此类的实例才能使用。例如
class student
{
private:
int admno;
char sname[20];
class Student_Marks
{
private:
float eng,math,science,computer,Hindi;
float total;
public:
void sMARKS()
{
cout<<"Please enter marks of english,maths,science,computer,science and hindi\n ";
cin>>eng>>math>>science>>computer>>Hindi;
}
float cTotal()
{
total=eng+math+science+computer+Hindi;
return total;
}
};
Student_Marks m_marks; // marks of this student
您的代码的另一个问题是您输入输入的方法极其缺乏错误检查...
答案 1 :(得分:0)
您的Student_Marks
只是一个类定义。在Student_Marks
中没有student
类的对象,就无法调用其成员(例如cTotal()
)。
您可以查看下面的示例代码:
class student
{
private:
int admno;
// better std::string here: what would you do if the name exceeds 20 char?
char sname[20];
class Student_Marks {
// ... code
};
Student_Marks student; // create a Student_Marks object in student
public:
// ...other code!
void setStudent()
{
student.sMARKS(); // to set the `Student_Marks`S members!
}
void showData() /* const */
{
// ... code
std::cout << "Total Marks :" << student.cTotal(); // now you can call the cTotal()
}
};