[英]How to use template and OOP in C++?
我希望對一組結構(例如加法)執行操作,如以下示例所示。 程序給出錯誤, 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()) );
...
}
我應該得到一對時間,並計算出該時間的作用力。
那里沒有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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.