简体   繁体   中英

Boost.Python - error with parametrized constructor

I have got a toy class from tutorialspoint in a file test.h:

class Box {
   public:

      Box(int l, int b, int h)
      {
        length = l;
        breadth = b;
        height = h;       
      }

      double getVolume(void) {
         return length * breadth * height;
      }
      void setLength( double len ) {
         length = len;
      }
      void setBreadth( double bre ) {
         breadth = bre;
      }
      void setHeight( double hei ) {
         height = hei;
      }

   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};

In the another file I have:

BOOST_PYTHON_MODULE(test)
{
  namespace python = boost::python;

  python::class_<Box>("Box")
    .def("setLength",  &Box::setLength )
    .def("setBreadth", &Box::setBreadth)
    .def("setHeight",  &Box::setHeight )
    .def("getVolume",  &Box::getVolume );
}

When I compile this code I get the error message about the Box class constructor:

/usr/include/boost/python/object/value_holder.hpp:133:13: error: no matching function for call to ‘Box::Box()’
             BOOST_PP_REPEAT_1ST(N, BOOST_PYTHON_UNFORWARD_LOCAL, nil)
             ^

What am I missing?

Do I need to write the constructor paramaters in BOOST_PYTHON_MODULE()? If so, how to do it?

You dont have a default constructor and you are missing the one you declared:

BOOST_PYTHON_MODULE(test) {
  namespace python = boost::python;

  python::class_<Box>("Box", boost::python::init<int, int, int>())
    .def("setLength",  &Box::setLength )
    .def("setBreadth", &Box::setBreadth)
    .def("setHeight",  &Box::setHeight )
    .def("getVolume",  &Box::getVolume );
}

The compiler is complaining that Box doesn't provide a default constructor BOOST_PYTHON_MODULE needs:

 no matching function for call to 'Box::Box() 

Simply define one:

class Box {
public:
    Box() = default;
// [...]
};

Additionnaly, you can checkout mohabouje's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM