Could you tell me what is wrong with my class constructor? Code:
CVector::CVector (int size_)
{
if (size_ > 0)
{
this->size = size_;
this->data = new double[size];
for (int i = 0; i < size; i++)
{
(*开发者_运维知识库this)(i) = i;
}
}
cout << "constructor end" << endl;
return;
}
Usage example:
tvector = CVector(6);
I get an access violation after "constructor end"
output.
Update: Constructor call was incorrect. Using
CVector tvector(6);
worked.
I think you want: this->data[i] = i
;
I'm going to assume you didn't add a copy constructor and the destructor frees some memory that you happened to stomp on with some other code.
You do not need a return
statement at the end of a constructor's body.
Constructors do return a value, but that is a more detailed explanation for another time.
I assume that by
(*this)(i) = i;
you actually meant
this->data[i] = i;
Right?
精彩评论