私はC++を初めて使用し、次のことを実行しようとしています。
「sim」という単純なクラスがあります。型クラス「sim」の10個の要素の配列を作成したいと思います。だから私は使用しましsim** a = new sim*[10]
た。
次に、ループで実行し、のような新しい要素を作成しますa[i]=new sim(i)
。しかし、後で各a [i]の値(フィールド)を印刷しようとすると、それ以外の値が得られません。
コードは次のとおりです。
#include "stdafx.h"
#include <iostream>
using namespace std;
class sim{
private:
int x;
const int y;
public:
sim();
sim(int z);
~sim();
void showInfo();
sim& operator=(const sim& s);
};
sim::sim():y(10),x(0)
{}
sim::sim(int z):y(10),x(z)
{}
sim::~sim()
{}
void sim::showInfo()
{
cout<<"x="<<x<<", y="<<y<<endl;
}
sim& sim::operator=(const sim& s)
{
x=s.x;
return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
sim** a = new sim*[10];
for(int i=0;i<10;i++)
{
a[i]= new sim(i);
}
for(int i=0; i<10; i++)
(*a)[i].showInfo();
getchar();
return 0;
}
そして、ここに間違った出力があります:
x=0, y=10
x=-33686019, y=-830047754
x=-33686019, y=-572662307
x=1869774733, y=201385040
x=725928, y=726248
x=1423328880, y=11
x=24, y=2
x=55, y=-33686019
x=4814584, y=-1
x=0, y=0
Yは常に10であり、xは0〜9である必要があります。私は何が間違っているのですか?ありがとう!