首页 > 解决方案 > 如何在外部类中调用内部类的函数?

问题描述

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()

我在访问外部类中的内部类函数时出错。

标签: c++classoopinner-classesmember-functions

解决方案


只要您将其称为“嵌套类”而不是内部类,您就可以在语言指南中找到适当的参考。它只是封闭类范围内的类型定义,您必须创建此类的实例才能使用。例如

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

您的代码的另一个问题是您输入输入的方法非常缺乏错误检查......


推荐阅读