试图理解c ++类之间的组合

时间:2013-05-16 02:19:13

标签: c++ class constructor composition

我很难理解如何在C ++类之间正确执行组合。以下是我遇到困境的一个例子:

#include <iostream>

using namespace std;

class Super
{
private:
    int idNum;
    string Name;
public:
    Super(int, string);
    void setSuper();
};

Super::Super(const int id, const string superName)
{
    idNum = id;
    Name = superName;
}

class Sidekick
{
private:
    int sideIdNum;
    string sideName;
    Super hero;
public:
    Sidekick(int, string, Super);
    void setSidekick();
};

int main()
{
    Super sm;
    Sidekick sk;

    sm.setSuper();
    sk.setSidekick();

    return 0;
}

void Super::setSuper()
{
    int superID;
    string sname;

    cin >> superID;
    cin >> sname;

    Super(superID, sname);
}

void Sidekick::setSidekick()
{
    int id;
    string siName;
    Super man;

    cin >> id;
    cin >> siName;
    //How do I perform action that automatically obtains the attributes 
    //from the object "hero" from Super?
}

1 个答案:

答案 0 :(得分:1)

要从Super类获取属性,您需要提供getter帮助程序。以下是一个例子:

using namespace std;

class Super
{
private:
    int idNum;
    string Name;
public:
    Super(int, string);
    void setSuper();
    int getId() {return idNum;}   // added here
    string getName() {return Name;} // added here
};

...

void Sidekick::setSidekick()
{
    int id;
    string siName;
    Super man;

    cin >> id;
    cin >> siName;
    //How do I perform action that automatically obtains the attributes 
    //from the object "hero" from Super?

    // Use yours helper here
    cout << hero.getId();
    cout << hero.getName();
}

顺便说一下,你不能像以前那样调用构造函数。您至少有两种选择,要么在创建对象时设置属性,要么提供setter助手来执行此操作。