继承和私有变量C ++

时间:2016-04-02 20:39:50

标签: c++ class inheritance

您好我刚开始使用C ++而且我想知道为什么我会收到此错误:C2248:本科:本科生无法在班级“本科生”中访问私人变量。

这是我的 student.h 课程,本科继承自

#ifndef _STUDENT_H_
#define _STUDENT_H_

#include <string>
using namespace std;

class Student {
private:
    // private local variables
    string fname, lname;
    int grade;
    int edu;

public:
    Student(string f, string l, int grade, int edu); // constructor
    string getFirstName(); // accessor
    string getLastName(); // accessor
    int getGrade(); // accessor
    int getEdu(); // accessor

    // Q1: Friend Function Change Grade
    // Declare a friend function named changeGrade which takes 2 parameters and has no return value.
    // The first parameter is a pointer to a Student, and the second is an integer.
    // See the helper function in hw09.cpp for proper use of this function.
    friend void changeGrade(Student *s, int newGrade){}
    virtual void displayInfo(){ }
};

#endif // _STUDENT_H_

Student.cpp

#include "Student.h"

Student::Student(string f, string l, int g, int e) {
    fname = f;
    lname = l;
    grade = g;
    edu = e;
}

string Student::getFirstName() { // accessor implimentation
    return fname;
}

string Student::getLastName() {
    return lname;
}

int Student::getGrade() {
    return grade;
}

int Student::getEdu() {
    return edu;
}

最后 Undergraduate.h

// Q2a : Create Undergraduate Class

// Create a child class of the Student class named 'Undergraduate'
// See the add function in hw09.cpp for proper use of this function.
class Undergraduate : public Student{
private:
    Undergraduate(string f, string l, int grade, int edu): Student(f,l,grade,edu){

    }
    virtual void displayInfo(){ }
};
// Declare constructor which accepts the same 4 parameters as the parent class Student.
// Pass the 4 parameters to the super constructor in the Student class.

现在我明白私有变量只能由该类成员访问,但是家庭作业要求我使用与父类相同的参数,这让我感到困惑,所以有办法解决这个问题吗?真的在网上发现任何类似于这个特定任务的东西。

1 个答案:

答案 0 :(得分:0)

由于你的Undergraduate(string f, string l, int grade, int edu): Student(f,l,grade,edu)构造函数是私有的,你如何实例化这个类?