如何实现操作员在层次结构中的使用?

雨伞

我有一个Base带有几个派生类的类:

class Base {
private:
    long id;
public:
    Base() {}
    ~Base() {}
    Base &operator = (long temp) {
        id = temp;
        return *this;
    }
};

template <class C>
class Temp1 : public Base {
public:
    Temp1() {}
    ~Temp1() {}
    //do something;
};

template <class C>
class Temp2 : public Base {
public:
    Temp2() {}
    ~ Temp2() {}
    //do something;
};

class Executor1 : public Temp1<int> {
public:
    Executor1() {}
    ~Executor1() {}
};

class Executor2 : public Temp2<char> {
public:
    Executor2() {}
    ~Executor2() {}
};

我希望那些课程能得到支持operator =
例如:

int main()
{
    long id1 = 0x00001111, id2 = 0x00002222;
    Executor1 exec1;
    Executor2 exec2;

    exec1 = id1;  //exec2.id = id1;
    exec2 = id2;  //exec2.id = id2;
}

我定义operator =Base谁的声明中Base &operator = (long);

但是显然有一个问题=无法派生类。因此,我必须定义operator =完全对每个对象执行相同的操作Executor

如何Base更好地处理这种情况

朱利安·H

您必须将= -operator拉入类的范围:

class Base
{
public:
    long id;

    Base& operator=(long id)
    {
        this->id = id;
        return *this;
    }
};

class Temp2
    : public Base
{
public:
    using Base::operator=;
};

您必须将operator =拉入范围,因为隐式生成的Temp2的副本operator =隐藏了Base的operator =。从@Angew的评论中得到了这个提示。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章