简体   繁体   中英

invalid user-defined conversion error

I am creating simple program that stores kids that attends to certain classroom , each kid has an array that defines their friends.

I am experiencing

error: invalid user-defined conversion from 'Kids*' to 'Kids&&' [-fpermissive]|

error. i am using this code

struct Kids{
    int *friends;
    Kids(){};
    Kids( int n ){
        friends = new int[n];
    }
};
class Classroom{
    Classroom(){
        cin >> size;
        kids = new Kids[ size ];
        for(int i = 0; i < size ; i++){
            kids[i] = new Kids(i);
        }
    }
private:
    int size;
    Kids *kids;
};

Why is this line

kids[i] = new Kids[i];

considering by compiler as attempt to convert Kids* to Kids&& while i am creating a new instance of node eg dynamicly allocating it thus passing it as Kids*?

Thanks for help!

new Kids(i) creates a Kids object initialized by i and returns pointer to it.

kids[i] is a Kids object (lvalue), not a pointer.

Those types are simply not compatible.

The kids array is already allocated by the first instruction ( kids = new Kids[ size ]; ), there's no need to do it again.

If you want to initialize each kid with it's index, you should be able to just type:

kids[i] = Kids(i);

But you seem to breaking the rule of three/fize/zero , so YMMV.

By the way, instead of doing all the hard work yourself, you should let the library do it for you and use a collection/smart pointer instead of managing your resources manually. Use std::vector<Kids> or std::unique_ptr<Kids[]> , whichever fits your needs.

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