“class :: data member is private”错误

时间:2013-06-29 08:52:23

标签: c++

谁可以帮助检查我的“class :: data member is private”错误。

#include <iostream>

using namespace std;

class Marks
{
    private:
            char * name;
            char * grade;
            float gpa;

    public:
           char* set_name(char * n)
           {

                name=n;
                cout<<"Enter name   :";
                cin>>name;

                return name;

           }

           float set_gpa(float g)
           {

                gpa=g;
                cout<<"Enter CGPA   :";
                cin>>gpa;

                return gpa;

           }

           char set_grade()

           {

                if(gpa>=3.00&&gpa<=4.00)
                {
                    grade[1]='A';
                }

                else if(gpa>=2.00&&gpa<=2.99)
                {
                    grade[1]='B';
                }

                else if(gpa>=0.00&&gpa<=1.99)
                {
                    grade[1]='F';
                }

                else
                {
                    cout<<"error"<<endl;
                }

                return grade[1];
           }
}M1;


int main()
{


    char name[20];
    char grade[1];
    float gpa;

    cout<<"=================================="<<endl;
    cout<<"         ENTER INFORMATION        "<<endl;
    cout<<"=================================="<<endl;

    M1.set_name(name);
    M1.set_gpa(gpa);
    M1.set_grade();

    cout<<"=================================="<<endl;
    cout<<"            RESULT SLIP           "<<endl;
    cout<<"=================================="<<endl;

    cout<<"Name     : "<<M1.name;
    cout<<"GPA      : "<<M1.gpa;
    cout<<"Grade    : "<<M1.grade;

    return 0;

}

错误列表

In function 'int main()':|
Line 9|error: 'char* Marks::name' is private|
Line 85|error: within this context|
Line 11|error: 'float Marks::gpa' is private|
Line 86|error: within this context|
Line 10|error: 'char* Marks::grade' is private|
Line 87|error: within this context|
Line 70|warning: unused variable 'grade'|
||=== Build finished: 6 errors, 1 warnings ===|

1 个答案:

答案 0 :(得分:2)

查看class Marks的定义:

private:
        char * name;
        char * grade;
        float gpa;

所有三个成员都被声明为私有,这意味着它们只能由类的成员函数访问 - 例如,在set_函数中完成。如果要访问类本身上下文之外的数据,请定义get_函数或公开数据 - 具体取决于您要执行的操作。

此外,由于这是C ++,您应该使用std::string作为字符串。