把Python嵌入C++的运算符重载的操作步骤详解


把Python嵌入C++的运算符重载中你如果在C++中对相关运算符重载后,把Boost.Python传给Python时,你就可以将以下的代码将Msg类的“+”运算符重载,然后通过“.def(self + self)”传递给Python。

  1. class Msg:public Message  
  2. {  
  3. public:  
  4. int count;  
  5. Msg(std::string m):Message(m)  
  6. {  
  7. }  
  8. void setcount(int n)  
  9. {  
  10. count = n;  
  11. }  
  12. int getcount()  
  13. {  
  14. return count;  
  15. }  
  16. int operator+ (Msg x) const  
  17. {  
  18. int r;  
  19. r = count + x.count;  
  20. return r;  
  21. }  
  22. };  
  23. BOOST_PYTHON_MODULE(Message)  
  24. {  
  25. class_<Message>("Message",init<std::string>())  
  26. .add_property("msg",&Message::get,&Message::set);  
  27. class_<Msg, bases<Message> >("Msg",init<std::string>())  
  28. .def("setcount", &Msg::setcount)  
  29. .def("getcount", &Msg::getcount)  
  30. .def(self + self);  
  31. }  

把Python嵌入C++的运算符重载中对于其他的运算符重载也可以使用同样的方法,如下所示。

.def(self - self) // 相当于_sub_方法

.def(self * self) // 相当于_mul_方法

.def(self /self) // 相当于_div_方法

.def(self < self); // 相当于_lt_方法

以上就是对Python嵌入C++的运算符重载相关的内容的介绍,望你会有所收获。

相关内容

    暂无相关文章

评论关闭