[英]C++ Object Array Pointer
I am new to C++ arrays and pointer and came across a few problems.我是 C++ 数组和指针的新手,遇到了一些问题。 I have some inquiries for the following code I wrote.我对我编写的以下代码有一些疑问。
Version 1:版本 1:
int main()
{
string a, b;
int age;
Dog d[5];
Dog *p = new Dog[5];
for (int i = 0; i < 5; i++)
{
d[i].setwe(3 * i);
d[i].setag(i);
p[i] = Dog(d[i]);
}
p[5]->showCnt();
//^^^^^^^^^^^^^^ Error above
for (int j = 0; j < 5; j++)
{
delete [] p;
}
return 0;
}
Version 2:版本 2:
int main()
{
string a, b;
int age;
Dog d[5];
Dog *p[5];
for (int i = 0; i < 5; i++)
{
d[i].setwe(3 * i);
d[i].setag(i);
//p[i] = Dog(d[i]);
p[i] = &d[i];
}
p[5]->showCnt();
return 0;
}
From what I understand I might have written wrongly in version 1 but I want to understand why p is not seen as a pointer in version 1?据我所知,我可能在版本 1 中写错了,但我想了解为什么 p 在版本 1 中不被视为指针?
This is the hint I got from error: base operand of '->' has non pointer-type 'Dog' .这是我从错误中得到的提示: '->' 的基操作数具有非指针类型 'Dog' 。
I am also unsure which is a better way(version 1 or version 2) to copy an object array to a pointer object array.我也不确定哪个是将对象数组复制到指针对象数组的更好方法(版本 1 或版本 2)。 I would like to apologise in advanced if I have understood it wrongly.如果我理解错误,我想提前道歉。 Thank you.谢谢你。
p[5]->showCnt()
is ilegal because your array of objects has only 5 positions, starting by 0 and ending on 4. So, you just have to replace p[5]->showCnt()
by p[4]->showCnt()
. p[5]->showCnt()
是非法的,因为您的对象数组只有 5 个位置,从 0 开始到 4 结束。因此,您只需将p[5]->showCnt()
替换为p[4]->showCnt()
。
About the better version to use, use version 2 if you want to work with static sizes and use version 1 if you want to manage p
dynamically to work with more than 5 objects at some moment of your program runtime.关于更好的版本,如果您想使用静态大小,请使用版本 2,如果您想动态管理p
以在程序运行时的某个时刻使用 5 个以上的对象,请使用版本 1。 Short answer: version 1 is better!简短回答:版本 1 更好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.