0

我希望对一组结构执行操作,例如加法,如下例所示。程序报错,no match for 'operator+' (operand types are 'Gravity' and 'Friction')。如何正确实施?

#ifndef FORCE_HPP
#define FORCE_HPP

struct Physics{    // not sure if this is needed

  struct Gravity{   // force type 1, which computes gravity

    int operator()(double t) {   //gravity force is computed based on a parameter t, and returns an int
        ...
        return Fg;
    }
};

  struct Friction{    // force type 2, which computes friction

    int operator()(double t) {   //friction force is computed based on parameter t, and returns an int
        ...
        return Fs;
    }
};

  template< typename F1, typename F2>
  Point make_physics(F1 first, F2 second){   // there can be 2 gravity forces, 2 friction forces, or 1 gravity and 1 friction force in a problem. As a result, use a template
    return first + second;
  }

};
#endif

如果程序正常工作,当我执行以下操作时

int main(){
...
make_pair(t, make_physics(Gravity(), Friction()) );
...
}

我应该得到一对时间和为那个时间计算的力。

4

1 回答 1

3

那里没有 OOP,而且您从未提到该程序应该做什么。但是朝着最明显的方向运行并应用快速修复,

#ifndef FORCE_HPP
#define FORCE_HPP

namespace Physics{ // use a namespace, not an unusable struct

  struct Force { // OOP base class for various forces
    double value; // one dimension for now

    operator double () { // implicitly convert to a scalar equal to magnitude
      return value;
    }
  };

  struct Gravity : public Force {
  };

  struct Friction : public Force {
  };

  template< typename F1, typename F2>
  double add_scalars(F1 first, F2 second){ 
    return first + second; // sort of pointless, but there you have it
  }

}
#endif
于 2013-03-24T02:51:56.397 回答