简体   繁体   中英

(C++) Accessing private member variables from a private base class

So my program requires the base class Media to have the members set to private as well as the constructor. I can't make them protected or public, thanks.

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;
}

Base class members cannot be used in initializer lists :

In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members.

However you can call the constructor of the base class:

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)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM