我很难理解如何正确执行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?
}

最佳答案

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

08-16 08:24