在Visual Studio中開發我的小示例時,我遇到了C++中未知的問題,並且在調試很多次後,我仍然無法找出問題出在哪裏,請幫我解決這樣的:Visual Studio C++中的運行時錯誤
這裏是我的Header.h:
#pragma once
#include <iostream>
#include <vector>
#include <string>
using namespace std;
這裏是我的Team.h:
#pragma once
#include "Header.h"
class Driver;
class Team
{
private:
string quocGia;
string ten;
int soLanVoDich;
vector<Driver*> ds_nguoi_dua;
public:
Team();
Team(string quocGia, string ten, int soLanVD);
~Team();
void AddRacer(Driver* myD);
void AddRacer(string ten, string quocTich, int slThang, int slVD, Team* tenTeam);
string getName();
};
現在是Team.h實現:
#include "Team.h"
Team::Team()
{
}
Team::Team(string ten, string quocGia, int soLanVD){
this->quocGia = quocGia;
this->ten = ten;
this->soLanVoDich = soLanVD;
}
string Team::getName(){
return this->ten;
}
Team::~Team()
{
}
void Team::AddRacer(Driver* myD){
this->ds_nguoi_dua.push_back(myD);
}
class Driver{
public:
Driver(string myTen, string quocTich, int slThang, int slVD, Team* tenTeam);
};
void Team::AddRacer(string myTen, string quocTich, int slThang, int slVD, Team* tenTeam){
Driver* myD = new Driver(myTen, quocTich, slThang, slVD, this);
this->ds_nguoi_dua.push_back(myD);
}
接下來,我定義Driver類:
// Driver.h
#pragma once
#include "Header.h"
class Team;
class Driver
{
private:
string hoTen;
string quocTich;
int soLanThang;
int soLanVoDich;
string tenTeam;
static int diem;
public:
Driver();
Driver(string hoTen, string quocTich, int soLanThang, int soLanVoDich, Team* tenTeam);
~Driver();
};
和實現爲:
#include "Driver.h"
int Driver::diem = 0;
Driver::Driver()
{
this->hoTen = "";
this->quocTich = "";
this->soLanThang = 0;
this->soLanVoDich = 0;
}
Driver::~Driver()
{
}
class Team{
public:
string getName();
};
Driver::Driver(string mHoTen, string mQuocTich, int soLanThang, int slVD, Team* team){
this->hoTen.assign(mHoTen);
this->quocTich.assign(mQuocTich);
this->soLanThang = soLanThang;
this->soLanVoDich = slVD;
this->tenTeam.assign(team->getName());
}
我對車手和車隊的包裝:
#pragma once
#include "Driver.h"
#include "Team.h"
#include <algorithm>
using namespace std;
class F1WorldFinal
{
public:
F1WorldFinal();
~F1WorldFinal();
};
而且這是主要類別:
#include <cstdlib>
#include <iostream>
#include "F1WorldFinal.h"
using namespace std;
int main(){
Team* teamRedBull = new Team("Red Bull", "Austrian", 4);
Driver* driver = new Driver("David Coulthard", "British", 13, 0, teamRedBull);
teamRedBull->AddRacer(driver);
// The problem happens here.
teamRedBull->AddRacer("Sebastian Vettel", "German", 42, 4, teamRedBull);
return 0;
}
但改變問題行到後:
teamRedBull->AddRacer(new Driver("Sebastian Vettel", "German", 42, 4, teamRedBull));
一切運作良好。
你可以花時間解釋爲什麼發生這種情況,我有調試,事實證明問題是在xstring @@,所以我真的不能解決這個問題。
此運行時錯誤消息的文本是什麼?你的調試器告訴你什麼? –
退出或至少減少使用'new'。例如,不需要'main'使用'new'。 C++不是Java。另外,您發佈的其他代碼中不需要「新」。您可以簡單地創建值對象。 – PaulMcKenzie
無關,你會長期爲自己做一個忙:「爲什麼」使用命名空間標準「被認爲是不好的做法?」](https://stackoverflow.com/questions/1452721/why-is-using -namespace-std-considered-bad-practice) – WhozCraig