C++ 如何将类对象指定给类
我需要在main()中创建一个对象Pokemon 将它分配到类PokemonWorld中,让PokemonWorld决定这个Pokemon需要去哪个Pokemon安装 我分别获取数据(获取名称和hp)和集合数据(获取口袋妖怪类) 但两者都失败了C++ 如何将类对象指定给类,c++,C++,我需要在main()中创建一个对象Pokemon 将它分配到类PokemonWorld中,让PokemonWorld决定这个Pokemon需要去哪个Pokemon安装 我分别获取数据(获取名称和hp)和集合数据(获取口袋妖怪类) 但两者都失败了 #include <iostream> #include <cstring> #include <iomanip> using namespace std; class Pokemon { public:
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class Pokemon {
public:
Pokemon() {};
Pokemon(char x[], int n) {
strncpy_s(name, x, 10);
hp = n;
};
private:
char name[10];
int hp;
};
class PokemonStation {
private:
Pokemon **list= new Pokemon*[1000];
public:
PokemonStation() {};
PokemonStation(int x) {
id = x;
};
int id;
void assigntoList(int i,Pokemon x)
{
if (i > 0)
i--;
list[i] = new Pokemon(x);
cout << "creat" << list[i];
};
};
class PokemonWorld {
private:
char name[10];
public:
PokemonStation s1;
PokemonStation s2;
PokemonWorld() {};
PokemonWorld(char x[], int y=1, int z=2) {
strncpy_s(name, x, 10);
PokemonStation s1(y);
PokemonStation s2(z);
};
const char* const getName() const{
return name;
};
void assigntoStation(int i,Pokemon x) {
if (i == 0 || i % 2 == 0)
s1.assigntoList(i, x);
else
s2.assigntoList(i, x);
};
};
void main() {
int number,hp,i;
char name[10];
cout << "What is the World Name ?" <<endl;
cin >> name;
PokemonWorld world(name);
cout << "Please input the number of Pokemon in the " << world.getName() <<" world:" << endl;
cin >> number;
Pokemon **mon = new Pokemon*[number];
cout << "Please input the characteristics of all Pokemon: Name HP" << endl;
for (i = 0;i < number;i++)
{
cin >> name >> hp;
mon[i] = new Pokemon(name, hp);
world.assigntoStation(i,*(mon[i]));
}
for (i = 0;i < number;i++)
cout << "world is " << world.getName() << endl;
system("pause");
};
#包括
#包括
#包括
使用名称空间std;
类口袋妖怪{
公众:
口袋妖怪(){};
口袋妖怪(字符x[],整数n){
strncpy_s(姓名,x,10);
hp=n;
};
私人:
字符名[10];
int-hp;
};
类口袋妖怪{
私人:
口袋妖怪**列表=新口袋妖怪*[1000];
公众:
PokemonStation(){};
口袋妖怪(int x){
id=x;
};
int-id;
无效分配列表(内部i,口袋妖怪x)
{
如果(i>0)
我--;
列表[i]=新口袋妖怪(x);
在C++中,你应该使用动态的事物列表和文本。如果你知道java,这些代码就像<代码> ARARYLIST/<代码>和String < /C> >(使用这些,请确保你的代码>包含< <代码> >代码> <代码>和<代码> <代码> > < /P>
例如,您的口袋妖怪
类,用名称
重写为字符串
:
class Pokemon {
public:
Pokemon() {}
Pokemon(string name, int hp):name(name), hp(hp) { // construct the fields directly
}
private:
string name;
int hp;
};
以及您的PokemonStation
类,使用vector
为Pokemon列表重写:
class PokemonStation {
private:
vector<Pokemon> list;
public:
PokemonStation() {}
PokemonStation(int x):id(x) {}
int id;
void assignToList(Pokemon x)
{
list.push_back(x); // add x to the list
}
};
只需确保你是cout
ing一个Pokemon
,而不是指向-Pokemon
(Pokemon*
)如果你想在C++中使用一个动态列表,你应该使用一个代替原始数组。也可以使用文本。你的程序中到底什么是不起作用的?当我试图在PokEnMeStand的函数分配器中打印出Pokimon时,我是否成功地把Pokimon分配到列表[I]中。,它会打印出列表[i]的地址并清除question@Adib问题是如何将类对象分配到类中
class Pokemon {
public:
...
friend ostream& operator<<(ostream& out, const Pokemon& p) {
out << p.name; // just print the name
return out;
}
...
};