我有一个建议,我们应该使用以下类别进行电阻计算(串联和并联):
class R1 {
protected:
double R , cost_in_euro ;
string unit ;
public :
R1(double R , const string & unit , double cost_in_euro);
R1(double R , double cost_in_euro);
R1(double R);
R1(const R1 & R);
R1 serie(const R1 & R1);
R1 parallel(const R1 & R1);
};
我的问题是关于serie和parallel函数。我应该如何使用仅将一个对象作为参数的函数添加2个电阻器?
答案 0 :(得分:2)
您只需要一个参数,因为该类包含一个R的信息,而参数包含另一个R的信息。
class R1 {
protected:
double R , cost_in_euro ;
string unit ;
public :
R1(double R , const string & unit , double cost_in_euro);
R1(double R , double cost_in_euro);
R1(double R);
R1(const R1 & R);
R1 serie(const R1 & other)
{
double total = other.R + R;
return R1(total);
}
R1 parallel(const R1 & other)
{
double r1 = other.R;
double r2 = R;
double total = (r1*r2)/(r1 + r2);
return R1(total);
}
};
答案 1 :(得分:0)
我应该如何使用仅需一个功能添加2个电阻器 一个对象作为参数?
您的类的两个实例(a和b)如何一起工作的示例:
// using 'lists' require -std=c++17 or newer
#include <iostream>
using std::cout, std::endl; // c++17
#include <iomanip>
using std::setw, std::setfill; // c++17
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
class R1
{
protected:
double m_R, m_cost;
string m_unit;
public :
R1(double R , const string & unit , double cost_in_euro);
R1(double R , double cost_in_euro);
R1(double R) // <<<<<<<<< dummy implmentation
: m_R (R)
, m_cost (9.9)
, m_unit ("a unit")
{
cout << "\n ctor R1(double) " << show() << endl;
}
R1(const R1 & R);
R1 serie(const R1& r2) // <<<<<<<<<< with diag cout
{
cout << "\n serie " << show() << "\n "
<< r2.show() << endl;
return (R1(r2.m_R + m_R));
}
R1 parallel(const R1& r2) // <<<<<<<<<< with diag cout
{
cout << "\n parallel " << show() << "\n "
<< r2.show() << endl;
return ((r2.m_R * m_R) / (r2.m_R + m_R));
}
string show() const
{
stringstream ss;
ss << " [m_R: " << m_R << " m_cost: " << m_cost
<< " '" << m_unit << "']";
return ss.str();
}
};
class F805_t
{
public:
int operator()()
{
R1 a(2.0);
R1 b(3.0);
a.serie(b); // <<<<<<<<< instance a using b
b.parallel(a); // <<<<<<<<< instance b using a
return 0;
}
}; // class F805_t
int main(int , char**) { return F805_t()(); }