我很难理解如何正确执行 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 助手来执行此操作。
关于c++ - 试图理解 C++ 类之间的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577980/