如何在层次结构中实现运算符,以实现复杂运算的嵌套与组合?
- 内容介绍
- 文章标签
- 相关推荐
本文共计285个文字,预计阅读时间需要2分钟。
javaclass Base { private long id;
public Base() {}
~Base() {}
Base operator=(long temp) { id=temp; return *this; }}
template class Cclass : public Base { public: Temp1() {}
Temp1() {}
// /d}
我有一个带有几个派生类的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的评论中得到了这个暗示.
本文共计285个文字,预计阅读时间需要2分钟。
javaclass Base { private long id;
public Base() {}
~Base() {}
Base operator=(long temp) { id=temp; return *this; }}
template class Cclass : public Base { public: Temp1() {}
Temp1() {}
// /d}
我有一个带有几个派生类的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的评论中得到了这个暗示.

