主な問題は、動的クラスを作成することです。私がやった:私はポインタptrが指すサイズ2の動的配列を作成しようとしているクラスとポインタ、どのように動作するのですか?
ptr = new animal[2];
。私はこれらの操作をしようとすると、 問題が発生する:
ptr[0].setspeed(9);
ptr++->setspeed(13);
私はDDD(GDBのグラフィカル)デバッガを使用していますが、私はPTRを表示するとき、私はそれが一つのオブジェクトを指す参照してください。速度を設定しようとすると、最初のものは動作しているように見えますが、2番目のものは動作しません(速度はデフォルトの0です)。印刷はゴミだけを取得します。
私は何が起こっているか分かりませんので、助けてください。
また私が行うとき:
ptr->print();
はそれがptr[0]
とptr[1]
、またはちょうどptr[0]
の両方に印刷することになっていますか?
さらに、ptr
と新しいダイナミッククラスの外観をすばやく描くことができますか?私がそれを見る方法は、配列を指すptrであり、配列の大きさは2で、それぞれには動物オブジェクトがあります。
#include <iostream>
using namespace std;
class animal
{
private:
int speed;
double position_x;
double position_y;
public:
animal() : speed(0), position_x(0), position_y(0)
{
}
animal (int v, double x, double y)
{
this->speed = v;
this->position_x = x;
this->position_y = y;
}
animal(const animal & g)
{
this->speed = g.speed;
this->position_x = g.position_x;
this->position_y = g.position_y;
}
~animal();
void print();
int getspeed() { return this->speed; }
int getx() { return this->position_x; }
int gety() { return this->position_y; }
void setspeed(int s) { this->speed = s; }
};
void animal::print()
{
cout << "speed: " << this->getspeed() << endl;
cout << "position_x: " << this->getx() << endl;
cout << "position_y: " << this->gety() << endl;
}
int main()
{
animal *ptr;
ptr = new animal;
ptr = new animal [2];
ptr[0].setspeed(9);
ptr++->setspeed(13);
ptr->print();
cout << ptr[0].getspeed() << endl;
cout << ptr[1].getspeed();
return 0;
}
ベスト・ヘルパー:動的配列をねじ込み、 'std :: vector'を得る。 – Xeo
ありがとう、しかし私はこれを理解したい(私は本当にこれを理解したいという意味です)、それが私がやっている理由です。 私は "ベクトル"に感謝 – Rave
"ptr =新しい動物; ptr =新しい動物[2];"たぶんこれは単にタイプミスかもしれませんが、メモリリークです。 – Duck