如何在外部类中调用内部类的函数?

问题描述

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...