简体   繁体   中英

using overloaded operator= does not compile

Hi I implemented an overload operator for = in my class but it is not compiling:

template<class T>
class OpClass {

  public:

    void Set(T val) {
        _val = val;
    }

    OpClass& operator=(T val) {
        this->Set(val);
        return *this;
    }

  protected:

    T _val;
}

class testOpClass {
    testOpClass() {
        OpClass<int>* intOpClass = new OpClass<int>();
        intOpClass = 6; // Does not compile I get following Error:
        // error: assigning to 'OpClass <int> *' from incompatible type 'int'
    }
}

This fails. Has it to do with that I am using an pointer ?

Has it to do with that I am using an pointer ?

Exactly. You're trying to assign into the pointer, not into the object you're pointing to. Would you expect this to work?

int *p = new int;
p = 42;

I guess not, you'd actually do

*p = 42;

Do the same in your case as well:

OpClass<int>* intOpClass = new intOpClass();
*intOpClass = 6;

Of course, remember this is C++ and don't use dynamic allocation if you don't need to. This would be even better:

OpClass<int> intOpClass;
intOpClass = 6;
testOpClass() {
    OpClass<int>* intOpClass = new OpClass<int>(); // Use OpClass class 
    *intOpClass = 6; // Use de-referencing 

    // ...
    delete  intOpClass ; //Make sure to release memory or better  
                         // avoid dynamic objects
}

you should use

class testOpClass {
    testOpClass() {
        OpClass<int>* intOpClass = new intOpClass();
        *intOpClass = 6;
    }
};

or

class testOpClass {
    testOpClass() {
        OpClass<int> intOpClass;
        intOpClass = 6;
    }
};

Both classes were lacking a ; . You are right. To call intOpClass = 6 it is not allowed to be a pointer. Simply dereference it or do not use a pointer.

template<class T>
class OpClass {

  public:

    void Set(T val) {
        _val = val;
    }

    OpClass& operator=(T val) {
        this->Set(val);
        return *this;
    }

  protected:

    T _val;
};

class testOpClass {
    testOpClass() {
        OpClass<int> intOpClass;
        intOpClass = 6; 
    }
};

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