把Python嵌入C++的運算符重載的操作步驟詳解
作者:佚名
把Python嵌入C++的運算符重載中的實際操作步驟,你對其是否感興趣?如果想在關于Python嵌入C++的運算符重載有更好的了解,那你可以瀏覽下面的文章。
把Python嵌入C++的運算符重載中你如果在C++中對相關運算符重載后,把Boost.Python傳給Python時,你就可以將以下的代碼將Msg類的“+”運算符重載,然后通過“.def(self + self)”傳遞給Python。
- class Msg:public Message
- {
- public:
- int count;
- Msg(std::string m):Message(m)
- {
- }
- void setcount(int n)
- {
- count = n;
- }
- int getcount()
- {
- return count;
- }
- int operator+ (Msg x) const
- {
- int r;
- r = count + x.count;
- return r;
- }
- };
- BOOST_PYTHON_MODULE(Message)
- {
- class_<Message>("Message",init<std::string>())
- .add_property("msg",&Message::get,&Message::set);
- class_<Msg, bases<Message> >("Msg",init<std::string>())
- .def("setcount", &Msg::setcount)
- .def("getcount", &Msg::getcount)
- .def(self + self);
- }
把Python嵌入C++的運算符重載中對于其他的運算符重載也可以使用同樣的方法,如下所示。
.def(self - self) // 相當于_sub_方法
.def(self * self) // 相當于_mul_方法
.def(self /self) // 相當于_div_方法
.def(self < self); // 相當于_lt_方法
以上就是對Python嵌入C++的運算符重載相關的內容的介紹,望你會有所收獲。
【編輯推薦】
責任編輯:佚名
來源:
互聯網