如何解决如何在外部类中调用内部类的函数?
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()
。
在访问外部类中的内部类函数时出现错误。
解决方法
只要将其称为“嵌套类”而不是内部类,您就可以在语言指南中找到适当的引用。这只是封闭类范围内的类型定义,您必须创建此类的实例才能使用。例如
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 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
您的代码的另一个问题是您输入输入的方法极其缺乏错误检查...
,您的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()
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。