【问题标题】:How to call a function of inner class in outer class?如何在外部类中调用内部类的函数?
【发布时间】:2020-08-13 22:20:36
【问题描述】:
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++ class oop inner-classes member-functions


【解决方案1】:

您的Student_Marks 只是一个类定义。如果student 中没有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()
    }
};

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

【讨论】:

    【解决方案2】:

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

    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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-18
      • 2013-04-26
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多