简体   繁体   English

使用重载 operator= 不编译

[英]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.当然,请记住这是 C++,如果您不需要,请不要使用动态分配。 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.调用intOpClass = 6不允许是指针。 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; 
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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