Microsoft Visual Studio에서 다음 코드를 실행하면 정크 값 (메모리 주소)이 출력되지만 g ++에서 실행되면 srand 변경과 같은 몇 가지 변경 사항이 있음). Visual Studio에서 작동하도록 수정하려면 어떻게해야합니까? 나는 경험을 코딩하는 데 몇 달 밖에 안 남았고,이 문제는 지금 당장 나를 괴롭혔다.Visual Studio에서 C++ 포인터에 문제가 발생했습니다 (g ++에서 작동).
class Vehicle
{
protected:
int * vin;
double * gasMileage;
public:
Vehicle();
Vehicle(int v, double g);
virtual void display(){cout<<"vin: "<<*vin<<endl<<"gasMileage: " <<*gasMileage<<endl;}
virtual double calcGasUsed(int milesDriven){return *gasMileage * milesDriven;}
int getVin(){return *vin;}
double getGasMileage(){return *gasMileage;}
void changeVin(int newvin) {vin=&newvin;}
void changeGasMileage(double newGasMileage){gasMileage=&newGasMileage;}
void drive();
};
class Suv:public Vehicle
{
protected:
bool *fourWDStatus;
double * fourWDGasMileage;
public:
Suv();
Suv(int v, double g,bool status, double fwdg);
void display();
double calcGasUsed(Suv&, int milesDriven);
bool getFourWDStatus(){return *fourWDStatus;}
double getfourWDGasMileage(){return *fourWDGasMileage;}
void changeFourWDStatus(bool status) {fourWDStatus=&status;}
void changeFourWDGasMileage(double newGasMileage){fourWDGasMileage=&newGasMileage;}
};
Vehicle::Vehicle()
{
this->vin=0000;
this->gasMileage=00;
}
Vehicle::Vehicle(int v, double g)
{
this->vin=&v;
this->gasMileage=&g;
}
Suv::Suv(int v, double g,bool status, double fwdg)
{
this->vin=&v;
this->gasMileage=&g;
this->fourWDStatus=&status;
this->fourWDGasMileage=&fwdg;
}
Suv::Suv()
{
this->vin=0000;
this->gasMileage=00;
this->fourWDStatus=false;
this->fourWDGasMileage=00;
}
void Suv::display()
{
Vehicle::display();
cout<<"fourWDStatus: "<<*fourWDStatus<<endl<<"fourWDGasMileage: "<<*fourWDGasMileage<<endl;
}
void Vehicle::drive()
{
int r=rand()%10000;
cout<<calcGasUsed(r)<<endl;
}
double Suv::calcGasUsed(Suv&, int milesDriven)
{
double x;
if (*fourWDStatus== true)
{
x= ((*fourWDGasMileage) * (milesDriven));
return x;
}
else
{
x=((*gasMileage) * (milesDriven));
return x;
}
}
void main()
{
cout << "test";
srand(NULL);
Suv A(300,12.2,false,16.6);
Suv B(200,15.5,false,20.1);
B.changeFourWDStatus(true);
Vehicle C(111,20.5);
C.drive();
C.display();
B.display();
Vehicle arrOfCars[]={A,B,C};
A.drive();
B.drive();
C.drive();
system("pause");
}
이 데이터 멤버에 대한 포인터를 사용해야합니다. 이것은 현재 수업에 대한 오래된 과제였습니다. 교수는 특별히 이것을 요구하고 그가 다시 물을 것이라고 압니다. – GuyPesto
@GuyPesto : 선생님이 포인터를 사용하라고 말했고 복사 생성자, 할당 연산자 및 소멸자에 대해 가르쳐주지 않은 것 같습니다. 또는 심지어 새롭고 삭제합니까? –
할당은 특히 복사 생성자, 소멸자 및 할당 연산자 생성을 요구하지 않았습니다. 내가 그들을 포함했다면 나는 아마 30 %를 잃어 버렸을 것이다. – GuyPesto