开发者

How to use private inheritance via constructing with arguments?

Some code like this:

class maven
{
private:
        string user开发者_Go百科name;
public:
        maven(string un)
        {
            username = un;
        }
};

class car : private maven
{
public:
       /... do something .../
};

Then I want a get a maven instance within the object car. But how can I construct the maven object with argument? I have looked up specification and annotation.


If you mean how to construct the maven part of the car object, do this with an initialization list:

class car : private maven
{
public:
    // This way
    car() : maven("foo") {
    }

    // Or this way
    car(string username) : maven(username) {
    }
};

It's worth noting that this way you do not get a maven instance within car; actually, car itself is a maven deep inside (although it doesn't tell anyone about it).

Unless you need access to maven's protected members for some reason, this way of doing things is not the best. You might want to consider aggregating an object of class maven instead, for example:

class car
{
private:
    maven m_maven;
public:
    // Initialize the member with a default parameter
    car() : m_maven("foo") {
    }

    // Or this way
    car(string username) : m_maven(username) {
    }
};

See this page of the C++ FAQ lite for a short discussion.


Create a constructor in car and initialise its base maven in the initialisation list.

class car : private maven
{
public:
    car(string un) : maven(un)
    {

    }
};


class car : private maven
{
public:
    car() : maven("some_username")
    {
    }
};


See Jon's answer for the difference between private inheritance and composition, but if you want to access the maven instance because, say, there is a function like this:

void baz(maven*);

Then in both cases, only members and friends of car can access the maven instance, so given a member of car eg car::zoo:

In the case of private inheritance:

car::zoo(){ baz(this); }

or in the case of composition:

car::zoo(){ baz(&m_maven); }

In both cases no other functions nor methods outside car, nor methods in classes derived from car can do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜