gpt4 book ai didi

c++ - 如何在 C++ 中使用模板和 OOP?

转载 作者:行者123 更新时间:2023-11-28 00:47:47 26 4
gpt4 key购买 nike

我希望对一组结构执行操作,例如加法,如下例所示。程序报错,不匹配“operator+”(操作数类型为“Gravity”和“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

关于c++ - 如何在 C++ 中使用模板和 OOP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com