如何在外部class中调用内部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 函数 cTotal(),在外部 class 函数 showData().

我在访问外部 class 中的内部 class 函数时遇到错误。

只要您将其称为“嵌套 class”而不是内部 class,您就可以在语言指南中找到适当的参考资料。它只是 类型 的定义,包含在 class 的范围内,您必须创建此类 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

您的代码的另一个问题是您输入输入的方法非常缺乏 error-checking...

您的 Student_Marks 只是一个 class 定义。如果 Student_Marks class 在 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()
    }
};

另请阅读:Why is "using namespace std;" considered bad practice?