How does copy constructor work?

后端 未结 5 807
感动是毒
感动是毒 2021-01-17 01:12

How does a copy constructor work in c++

Error 1 error C2064: term does not evaluate to a function taking 1 arguments c:\\users\\thuan\\dropbox\\homework\\css

5条回答
  •  走了就别回头了
    2021-01-17 01:26

    After you declare

    InSet object1;
    

    the object named object1 exists (created via the default constructor). Copy constructor (just like a regular constructor) creates a new object. Since the object already exists, the expression object1(object2); cannot be a copy-constructor call. For that, you need to declare your variables like this:

    InSet object2(9);
    InSet object1(object2);
    

    If you wanted to copy object2 to the already existing object1, you will need an assignment operator (InSet& InSet::operator=(const InSet& other);)

    Note: The compiler error is telling you that the expression (object1(object2); is a function call expression: you will need to define the function call operator (void InSet::operator()(const InSet& obj)) to make it compile (the return type could be anything else, not just void, depending on your need.) If you define the function call operator, you turn your object into what is called a functor

    The compiler error (term does not evaluate to a function taking 1 arguments) is correct, but misleading wrt. to your problem (but there is no way for the compiler to know you wanted to use the copy constructor, instead of a function call)

    Note: On many compilers the expression

    InSet object2(9);
    InSet object1 = object2;
    

    also results in a call to the copy constructor (instead of default-constructing the object and then calling assignment operator on it), if available -- this is a possible compiler optimization.

    Note: The declarations InSet object1; and InSet object2(9); are invalid if the only (regular) constructor you have is the one you listed, unless you have default values for the (regular) constructor's parameters in the class definition (where the constructor is declared), which you did not include.

提交回复
热议问题