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

スーパー クラスから属性を取得するには、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();
}

ところで、以前のようにコンストラクターを呼び出すことはできません。オブジェクトの作成時に属性をセットアップするか、このアクションを実行するセッター ヘルパーを提供するか、少なくとも 2 つの選択肢があります。

于 2013-05-16T02:38:15.310 に答える