简体   繁体   中英

Enforce assignment operator instead of copy constructor on initialization?

I'm putting together my own (silly) Scalars/List/Hash (perl-like..) thing in C++.

I've come across a point having to dereference a Scalar into a List, and it does not work when attempted in initialization.

List several default constructors, out of which 5 range from List() to List(Scalar, Scalar, Scalar, Scalar) .

List stuff(1, 2, 3);
Scalar aref = stuff; // List overloads the (Scalar) cast operator

// the following line is the unwanted thing..
List failist = aref; // uses List::List(Scalar), so same as `List failist(aref);`

// however, these work
List thisworks;
thisworks = aref;
thisworks.operator=(aref);

List header:

class List : public Thing {
    std::vector<Scalar> stuff;
public:
    List();
    List(Scalar s1); // this gets called because initialization
    List(Scalar s1, Scalar s2);
    List(Scalar s1, Scalar s2, Scalar s3);
    List(Scalar s1, Scalar s2, Scalar s3, Scalar s4);
    List &operator=(const Scalar &other); // but i want this

    /* some getters/setters cut away */

    operator Scalar();
};

I'd really like to use List mylist = listreference; , how do I ?

I'm wondering if you don't want List myList = scalar to invoke the constructor, then why do you have it in the first place?

Anyway, make it explicit as :

explicit List(Scalar s1);. 

That way, you would make the compiler to spit out error on line:

List myList = scalar; //error 

and then you will have chance to correct yourself, either by writing:

List myList(scalar); //ok

Or,

List myList; 
myList = scalar; //ok

Note that you cannot make List myList = scalar to invoke List& operator=(Scalar const&) , you can however implement one in terms of other, or both in terms of some common init function to avoid code duplication. The latter approach is better.

You can't do it. List mylist = listreference; means: create mylist object of type List with copy constructor. So you have 2 options:

  1. Implement copy constructor via opeartor=
  2. Do it with two lines of code: List mylist = listreference; mylist = listreference; List mylist = listreference; mylist = listreference;

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