![](/img/trans.png)
[英]How to declare friend with static function in Outer class inside the Inner class?
[英]How to call a function of inner class in outer class?
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();
}
};
我想调用内部 class function cTotal()
showData()
在外部 class ZC1C425268E68385D1AB4ZA4 显示
我在访问外部 class 中的内部 class function 时出错。
只要您将其称为“嵌套类”而不是内部 class,您就可以在语言指南中找到适当的参考。 它只是封闭类的 scope中的类型定义,您必须创建这样的 class 的实例才能使用。 例如
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
您的代码的另一个问题是您输入输入的方法非常缺乏错误检查......
您的Student_Marks
只是一个 class 定义。 如果在student
中没有 Student_Marks class 的Student_Marks
,则不能调用其成员(例如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()
}
};
另请阅读: 为什么“使用命名空间标准;” 被认为是不好的做法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.