以下代码会生成运行时错误,其中该类的调用方法不会生成任何结果。从C++中的类指针对象调用方法(字符串)
MAIN.cpp
:
#include "carClass.h"
#include <fstream>
#include <iostream>
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
string VIN;
int miles;
string dealer;
int price;
int main(int argc, char** argv) {
char command;
ifstream infile;
ofstream outfile;
//Checks if the data file exists
infile.open("base.txt", ifstream::in);
outfile.open("base.txt", ios_base::app);
cout << "Enter a command:" << endl;
cin >> command;
while (command != 'q')
{
switch (command)
{
case 'a':
{
cin >> command;
if (command == 'c')
{
//Gets user input
cin >> VIN >> miles >> dealer >> price;
//Creates new pointer variable with the user data
Car* vehicule = new Car(VIN, miles, dealer, price);
VIN=vehicule->getVin();
cout << "vehicule object VIN is: " << VIN;
//end of for loop
}//end of if loop
}//end of case loop
break;
}//end of switch
cout << "Enter a command:" << endl;
cin >> command;
}//end of while loop
outfile.close();
infile.close();
return 0;
}
这里是我尝试调用方法我对象的指针
VIN=(*vehicule).getVin();
我也试过
vehicule->getVin();
并没有奏效
这里我在哪里检查是否存储了任何内容并返回空白cout << "vehicule object VIN is: " << VIN;
如果你想看到这里你有两个源文件和头文件
carClass.cpp
:
#include "carClass.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
Car::Car()
{
string VIN;
int mileage=0;
string dealership;
int price=0;
string vinCode;
}
Car::Car(string vin, int miles,string carDealer, int dollars)
{
string VIN=vin;
int mileage=miles;
string dealership=carDealer;
int price=dollars;
string vinCode = VIN.substr(0,3);
}
void Car::addToBase(ofstream& file)
{
file << "c" << endl << VIN << endl << this->mileage << endl <<
this->dealership << endl << this->price << endl;
return;
}
carClass.h
:
#ifndef CAR_H
#define CAR_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Car {
public:
Car();
Car(string, int, string, int);
void addToBase(ofstream&);
string getVin(){return VIN;}
int getMiles(){return mileage;}
string getDealer(){return dealership;}
int getPrice(){return price;}
string getVinCode(){return vinCode;}
private:
string VIN;
int mileage;
string dealership;
int price;
string vinCode;
};
#endif
谢谢,现在向上投票。 – mastov