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()
我在访问外部类中的内部类函数时遇到错误。

最佳答案

您的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?

08-18 19:38
查看更多