(C ++)从私有基类访问私有成员变量

时间:2015-09-12 01:38:03

标签: c++ class inheritance

所以我的程序要求基类Media将成员设置为private以及构造函数。我不能让他们受到保护或公开,谢谢。

class Media
{
public:
    friend ostream &operator<<(ostream &output, const Media &Media)
    {
        output << Media.mId << " " << Media.mTitle << " " << Media.mYear << " "
                << Media.mRatings;
        return output;
    }
    Media(int id, string title, int year, int ratings);
//void printRating();
    friend class Movie;
private:

    int mId, mYear, mRatings;
    string mTitle;
};
Media::Media(int id, string title, int year, int ratings)
{
    mId = id;
    mTitle = title;
    mYear = year;
    mRatings = ratings;
}
class Movie: public Media
{
public:
    Movie(int id, string title, int year, string director);
    string mDirector;
};
Movie::Movie(int id, string title, int year, string director) :
        mId(id), mTitle(title), mYear(year), mDirector(director)
{
}

int main()
{

    Media *ptr[10];
    ptr[0] = new Movie(352, "Fight Club", 1999, "David Fincher");
//cout << *ptr[0]<<endl;
}

1 个答案:

答案 0 :(得分:0)

基类成员不能在initializer lists中使用:

  

在类的构造函数的定义中,成员初始化列表指定直接和虚拟基础子对象和非静态数据成员的初始化器。

但是你可以调用基类的构造函数:

Movie::Movie(int id, string title, int year, string director) :
    Media(id, title, year, 0), // 0 or or whatever default rating value should be
    mDirector(director)
{
}