c – 如何在层次结构中实现运算符使用?
发布时间:2020-12-16 09:21:43 所属栏目:百科 来源:网络整理
导读:我有一个带有几个派生类的Base类: class Base {private: long id;public: Base() {} ~Base() {} Base operator = (long temp) { id = temp; return *this; }};template class Cclass Temp1 : public Base {public: Temp1() {} ~Temp1() {} //do something;}
我有一个带有几个派生类的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; } 我在Base中定义operator =,其声明为Base& operator =(long);. 但是有一个问题显然是=无法派生类.所以我必须定义operator =完全对每个Executor做同样的事情. 如何以更好的方式在Base中处理这种情况? 解决方法
您必须将= -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 = of Base.从@Angew的评论中得到了这个暗示. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |