私は、ブーストバインドの派生クラスとの相互作用をテストする簡単な例を作成しました。Boost Mem_fnと派生クラスのメンバー関数へのアクセス
異なるgetarea関数を持つ2つのサブクラスを作成しました。私は予期していました
g1 = boost::bind(boost::mem_fn(&Shape::getarea), Rec)
矩形(10,20)の領域を印刷する代わりに '1'を印刷しました。代わりにRectangle::getarea
と書くと、同じことになります。他の機能などを入力しても同じ結果が表示されます。長方形
double sum(double h,double w){return h+w; }
と
g1 = boost::bind(boost::mem_fn(&Rectangle::sum), Rec,2,3)
質問1を使用します?なぜそれが戻らないが '1' のエラーに対するデフォルトの応答ということですか?
私の2番目の問題は同じことをg2に印刷することですが、Recは** iter、つまりオブジェクトのリストからの派生クラス型のオブジェクトに置き換えられました。 **のするClassTypeを返す方法がある場合は、私が思っていた:
g2= boost::bind(boost::mem_fn(& Shape::getarea , &(**iter));
質問2:GETAREAは、私は上記を得れば作業それだけで書くのは問題ないはずですが、仮想FCNあるので、 iter eg。 classof(** ITER)、その後はG2にそれを置く、すなわち
私はすべてのITERのためにもう一度、私が得た '1' の形状:: GETAREAを書き込むことによって、G2を走っg2= boost::bind(boost::mem_fn(& classof(**iter)::getarea , &(**iter));
。
#include <memory>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <boost/bind.hpp>
using namespace std;
class Shape {
public:
Shape(double h, double w) :height(h), width(w) {};
virtual double getarea() = 0;
double height;
double width; };
class Rectangle: public Shape {
public:
Rectangle(double h, double w): Shape(h,w) {};
double getarea() override { return height*width; } };
class Triangle : public Shape {
public:
Triangle(double h, double w) :Shape(h,w) {};
double getarea() { return height*width*0.5; }};
int main() {
//create objects
Rectangle Rec(10, 20);
Triangle Tri(2, 3);
//create boost bind function
boost::function<double(double, double)> g1;
g1 = boost::bind(boost::mem_fn(&Shape::getarea), Rec);
//print area and g
cout << Rec.getarea()<<" should be equal to " << g1<< '\n';
//create list
vector<shared_ptr<Shape>> Plist;
Plist.push_back(make_shared<Rectangle>(Rec));
Plist.push_back(make_shared<Triangle>(Tri));
//print each element from the vector list
for (auto iter = Plist.begin(); iter != Plist.end(); iter ++) {
boost::function<double(double, double)> g2;
g2= boost::bind(boost::mem_fn(& .... , &(**iter));
//where in dots we need Classtype_of_**iter::getarea
cout << (**iter).getarea()<<"should be equal to " << g2<< '\n';
}
}