编译器:C++ (g++)
当一个3伏特的直流电压施加在一个1.5欧姆的电阻上时,流过电阻的电流为2安培。电阻消耗的功率既可以通过P = UI计算,即3 * 2 = 6瓦特,也可以通过P = I²R计算,即 2² * 1.5 = 6瓦特。请设计Voltage电压类及Current电流类,并实现两个名字重载的computePower()函数,使得下述代码可以运行并产生期望的输出。
其中,Voltage和Current类应:①.包含一个私有的float类型的数据成员用于保存电压或电流值;②.提供一个合适的构造函数用于初始化对象;③.提供公有的value()函数用于访问私有的电压或电流值。
裁判测试程序样例:
输入样例:
输出样例:
P = UI = 3*2 = 6
P = IIR = 2*2*1.5 = 6
请注意:函数题只需要提交相关代码片段,不要提交完整程序。
//Project - Power
#include <iostream>
using namespace std;
//定义Voltage类
//定义Current类
//定义两个函数名重载的computePoweer()函数
int main() {
cout << "P = UI = 3*2 = "
<< computePower(Voltage(3),Current(2)) << endl;
cout << "P = IIR = 2*2*1.5 = "
<< computePower(Current(2),1.5) << endl;
return 0;
}
Ans:
#include <iostream>
#include <cmath>
using namespace std;
class Current;
class Voltage {
private:
double V;
public:
Voltage(double Vo) :V(Vo) {}
double getV() const {
return V;
}
};
class Current {
private:
double C;
public:
Current(double Cu) :C(Cu) {}
double getC() const {
return C;
}
};
double computePower(const Voltage& a, const Current& b) {
return a.getV()*b.getC();
}
double computePower(const Current& a, double b) {
return a.getC() * a.getC() * b;
}