Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;Python增强 我想用Python Boost公开一个C++好友函数到Python。_Python_C++_Boost - Fatal编程技术网

C++;Python增强 我想用Python Boost公开一个C++好友函数到Python。

C++;Python增强 我想用Python Boost公开一个C++好友函数到Python。,python,c++,boost,Python,C++,Boost,class Turtle{ friend const PV& GetHeading(const Turtle& t); friend const PV& GetLeft(const Turtle& t); friend const P& GetPoint(const Turtle& t); friend void SetPoint

     class Turtle{
               friend const PV& GetHeading(const Turtle& t);
               friend const PV& GetLeft(const Turtle& t);
               friend const P& GetPoint(const Turtle& t);
               friend void SetPoint(Turtle& t, const P& p);
               public:

               ...  

               private:
               PV h; 
               PV l; 

          };
在这里,我包装了PV和p类,因此没有问题。我试图像普通函数一样包装friend函数。像

          BOOST_PYTHON_MODULE(TurtleWrapper)
              {
                 class_<Turtle>("Turtle") 
                   .def("GetHeading",&Turtle::GetHeading) 
                   .def("GetLeft",&Turtle::GetLeft)
                   .add_property("h",&Turtle::GetHeading)
                   .add_property("l",&Turtle::GetLeft);
             }

因此,我假设这不是声明友元函数的方法,python boost的文档似乎也没有(或者至少我没有看到关于友元函数的注释)。非常感谢您提供的任何帮助。

仅看这段代码,不清楚为什么函数首先声明为
friend

friend
关键字用于向编译器指示给定函数或类能够访问为其定义的类的私有和受保护成员。
friend
函数不是类的成员

绑定函数时,可以指定,例如,
&Turtle::GetLeft
作为指向要绑定的函数的指针<但是,code>GetLeft不是
Turtle
的成员,它只是一个friend函数

查看您的绑定,您要做的是使诸如GetHeading/GetLeft之类的函数成为公共成员函数

因此,我假设您有如下情况:

class Turtle {
  friend const PV& GetHeading(const Turtle& t);
  // ...
};
// somewhere else in your code
const PV& GetHeading(const Turtle& t) {
  // getting heading here
}
class Turtle {
  public:
  // no need for friend declaration
  const PV& GetHeading() const {
    // move code into the class
  }
  // ...
};
我建议你这样写:

class Turtle {
  friend const PV& GetHeading(const Turtle& t);
  // ...
};
// somewhere else in your code
const PV& GetHeading(const Turtle& t) {
  // getting heading here
}
class Turtle {
  public:
  // no need for friend declaration
  const PV& GetHeading() const {
    // move code into the class
  }
  // ...
};
一旦您将函数重新编写为公共成员函数而不是友元非成员函数,您就可以如上所述绑定它们


可能值得注意的是,谨慎使用
朋友是一种很好的做法。如果使用不当,可能会破坏类的封装。查看一下

您是否正在尝试在不需要的地方使用
friend
关键字?将函数声明为
friend
通常意味着它不是类的一部分,这是一种允许类之外的函数访问私有/受保护成员的方法。因此,错误是有效的。我的意思是C++代码不是由我编写的,它是一个更大代码的一部分,这些函数确实被用作各种类的朋友,以便它们可以访问这些类的数据成员。所以我不知道是否要包装它们。但它们也用于这个名为Turtle的类中。所以我的问题是,它是否可以包装到python boost中,如果可以,我该如何做呢?感谢sneg给出了这个详细的答案。这确实很有帮助。