我的代码编译但抛出异常:“HealthCareProvider.exe 附加信息中发生类型为‘系统,访问冲突异常’的未处理异常:试图读取或写入 protected 内存......”帮助??
问题出在 print() 方法上。我不知道为什么。 迭代器只打印出一堆不同的数字(需要toString())
谦卑地,
迈克
#ifndef _HEALTHCAREPROVIDER_H
#define _HEALTHCAREPROVIDER_H
#include <string>
#include <iostream>
using namespace std;
class HealthCareProvider{
public:
//constructor
HealthCareProvider(const string &lname, const string &fname, const string &type, const int &yearsExperience, const string &coType):
lastName(lname),firstName(fname),providerType(type),yearsExp(yearsExperience),companyType(coType)
{
}
//Last Name
void setLastName(const string &lname){
lastName = lname;
}
string getLastName()const{
return lastName;
}
... etc.
//coType
void setCompanyType(const int &coType){
companyType = coType;
}
string getCompanyType()const{
return companyType;
}
void print() const {
cout<<"Name: "<< getLastName()<<", " <<getFirstName()<<"\nType : "<<getProviderType()<<"\nYears Experience: "<<getYearsExp()<<" \nCompany Type : "<<getCompanyType()<<endl;
}
virtual double billForTreatment() = 0;
private:
int yearsExperience, yearsExp;
string type, coType, lname, fname;
string lastName, firstName, providerType, companyType;
};
#endif
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <typeinfo>
#include <iterator>
#include "HealthCareProvider.h"
#include "Dentist.h"
using namespace std;
int main (){
string value;
cout << fixed << setprecision (2);
//populate
vector < HealthCareProvider*> healthCareProviders (6);
healthCareProviders [0]=new Dentist("Thatcher","Donald","Dentist",10, "sole proprietorship");
healthCareProviders [1]=new Dentist("Parker","Michelle","Dentist",5, "LLC");
healthCareProviders [2]= new Dentist("Bradford","Michael","Dentist",12, "LLC");
healthCareProviders [3] = new Dentist("Craig","Elizabeth","Dentist",4, "sole proprietorship");
for (size_t i=0; i<healthCareProviders.size(); i++){
healthCareProviders[i] ->print();
cout<<endl;
}
for (size_t j =0; j< healthCareProviders.size(); j++){
delete healthCareProviders [j];
}
cout<<"Pause . . ."<<endl;
cin>>value;
}
最佳答案
您正在创建一个大小为 6 的 vector ,但您只初始化了前 4 个条目。其余两个指针为 NULL
,这就是为什么在调用 healthCareProviders[i] ->print();
时会发生访问冲突。
一个简单的解决方案是使用 vector::push_back
根据需要添加元素,而不是提前指定大小:
healthCareProviders.push_back(new Dentist(...));
关于c++ - HealthCare Provider.exe 中发生类型为 'System, Access Violation Exception' 的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269938/