简体   繁体   中英

How to assign a pointer to object to another pointer to object of same class?

I have a class called arr and it has a function named _union written like this:

template<class T>
arr<T> *arr<T>::_union(arr<T> B) {
    arr<T> *C(this->length + B._length());
    bool isPresent = false;
    for (int i = 0; i < length; i++)
        C->push_back(this->get(i));
    for (int j = 0; j < B._length(); j++) {
        for (int k = 0; k < C->_length(); k++) {
            if (B.get(j) == C->get(k))
                isPresent = true;
        }
        if (!isPresent)
            C->push_back(B.get(j));
        isPresent = false;
    }

    return C;
}

The function returns a pointer of an object that was newly created inside this function's scope.

In main function, I wrote code like this:

arr<int> *a3 = a1._union(a2);
a3->display();

When I run, this gives me an error:

在此处输入图像描述

What is the problem here? If I don't use any pointers and just return normal object then everything is fine.

Please help me. Also I don't have any copy constructers inside the class. I am just trying to create my own array class with data and functions.

In this code

arr<T> *C(this->length + B._length());

C is a pointer and this->length + B._length() is an integer, hence the error. You can't assign an integer to a pointer.

I guess you were trying to write this code

arr<T> *C = new arr<T>(this->length + B._length());

This code allocates a new arr<T> object using new and calls the a constructor for that object using the integer parameter this->length + B._length() .

However is usually a bad idea to use dynamic allocation like this. You should think about redesigning your function without using pointers.

template<class T>
arr<T> arr<T>::_union(arr<T> B) {
    arr<T> C(this->length + B._length());
    ...
    return C;
}

This will require you to define a copy constructor etc for arr<T> . But that is normal C++ programming you shouldn't be reluctant to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM