【发布时间】:2019-03-24 14:57:09
【问题描述】:
我已经为它创建了一个对象和一个存储库。 当我尝试将对象插入存储库(使用我创建的插入函数)时,出现编译错误。
我试图插入到存储库中的类
class Payment{
private:
int day;
int amount;
char *type;
public:
Payment();
Payment(int day, int amount, char *type);
Payment(const Payment &p);
~Payment();
//getters
int getDay()const;
int getAmount()const;
char* getType()const;
//setters
void setDay(int day);
void setAmount(int amount);
void setType(char* type);
//operator
Payment& operator=(const Payment& other);
friend ostream& operator<<(ostream &os,const Payment &obj);
};
//copy constructor
Payment::Payment(const Payment & p){
this->day = p.day;
this->amount = p.amount;
if(this->type!=NULL)
delete[] this->type;
this->type = new char[strlen(p.type)+1];
strcpy_s(this->type, strlen(p.type) + 1, p.type);
}
//assignment operator
Payment& Payment::operator=(const Payment &other) {
this->day = other.day;
this->amount = other.amount;
this->type = new char[strlen(other.type) + 1];
strcpy_s(this->type, strlen(other.type) + 1, other.type);
return *this;
}
//destructor
Payment::~Payment(){
this->day = 0;
this->amount = 0;
if (this->type != NULL) {
delete[]this -> type;
this->type = NULL;
}
}
//Repository header
class Repository{
private:
vector<Payment> list;
public:
Repository();
int getLength();
void insert(const Payment& obj);
void remove(int position);
};
//Repository cpp
Repository::Repository(){
this->list.reserve(10);
}
//return the size of the list
int Repository::getLength() {
return this->list.size();
}
//add payment to list
void Repository::insert(const Payment &obj) {
this->list.emplace_back(obj);
}
//remove payment from list
void Repository::remove(int position) {
this->list.erase(this->list.begin() + position);
}
在我的主要功能中
char c[] = "some characters";
Payment pay = Payment(7,9,c);
Repository rep = Repository();
rep.insert(pay);
当我运行程序时出现错误“ 表达式:_CrtlsValidHeapPointer(block) "
【问题讨论】:
-
那不是编译器错误,那是运行时错误。第二,你为什么不用
std::string type;?那将解决您的问题。如果不是这样,这是如何实现“3 规则”的重复,即您缺少Payment的用户定义复制构造函数。 -
复制构造函数可以解决问题。我完全忘记了。我会试一试,然后回复结果。谢谢您的帮助! ^_^
-
请发布实现复制构造函数、赋值运算符和析构函数的代码。这就是问题所在。
std::vector要求您放置在向量中的类型具有正确的、无错误的复制语义。如果您使用std::string而不是char *,那么这将不是问题。既然你坚持使用char *,那么现在由你来编写所有这些函数,没有错误。 -
另外,请参阅the rule of 3。
-
@PaulMcKenzie 我也创建了复制构造函数,但仍然无法正常工作。我想使用动态分配。这不是比使用
std::string更快吗?你建议我使用std::string,那么什么时候应该使用string,什么时候应该使用char?即使我改变了类型,我也很想知道如何克服这个错误。
标签: c++ class object insert repository