开发者

Constructor return value

开发者 https://www.devze.com 2022-12-25 22:53 出处:网络
Could you tell me what is wrong with my class constructor? Code: CVector::CVector (int size_) { if (size_ > 0)

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消