0

我很难弄清楚如何在 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?
}
4

1 回答 1

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 助手来执行此操作。

于 2013-05-16T02:38:15.310 回答