我需要表示伏特、安培和瓦特及其关系(例如 W = V * I)。
这是我带来的,但看起来真的很冗长。关于如何使其更简洁的任何想法?
#include <stdio.h>
#include <iostream>
template<class T>
class double_val {
public:
explicit double_val(double val):_val(val) { };
double_val(const T& other) {
_val = other._val;
}
T& operator=(const T &other) {
_val = other._val;
return *this;
}
T operator+ (const T& other) const {
return T(this->_val + other._val);
}
T operator+ (double val) const {
return T(this->_val + val);
}
T operator- (const T& other) const {
return T(this->_val - other._val);
}
T operator- (double val) const {
return T(this->_val - val);
}
T operator* (const T& other) const {
return T(this->_val * other._val);
}
T operator* (double val) const {
return T(this->_val * val);
}
T operator/ (const T& other) const {
return T(this->_val / other._val);
}
T operator/ (double val) const {
return T(this->_val / val);
}
bool operator== (const T& other) const{
return this->_val == other._val;
}
bool operator!= (const T& other) const{
return this->_val != other._val;
}
bool operator > (const T& other) const{
return this->_val > other._val;
}
bool operator >= (const T& other) const{
return this->_val >= other._val;
}
bool operator < (const T& other) const{
return this->_val < other._val;
}
bool operator <= (const T& other) const{
return this->_val <= other._val;
}
void val(double val){
_val = val;
}
double val() const {
return _val ;
}
virtual const char* name() const = 0;
private:
double _val;
};
template<class T>
std::ostream& operator<<(std::ostream &os, const double_val<T> &t) {
return os << t.val() << " " << t.name();
}
class Amper:public double_val<Amper> {
public:
Amper(double val):double_val<Amper>(val) {}
const char* name() const {
return "Amper";
}
};
class Volt:public double_val<Volt> {
public:
Volt(double val):double_val<Volt>(val) {}
const char* name() const {
return "Volt";
}
};
class Watt:public double_val<Watt> {
public:
Watt(double val):double_val<Watt>(val) {}
const char* name() const {
return "Watt";
}
};
// Watt = I * V
Watt operator* (const Volt &v, const Amper& a) {
return Watt(a.val() * v.val());
}
Watt operator* (const Amper &a, const Volt& v) {
return Watt(a.val() * v.val());
}
// Volts = Watts/Ampers
Volt operator / (const Watt &w, const Amper& a) {
return Volt(w.val() / a.val());
}
// Ampers = Watts/Volts
Amper operator / (const Watt &w, const Volt& v) {
return Amper(w.val() / v.val());
}
int main(int argc, char **argv) {
using namespace std;
Watt w = Volt(66) * Amper(7);
Amper a = w / (Volt(646) * Volt(444));
cout << a << endl;
return 0;
}
(注意:我有意省略了 operator double(),因为我想避免像 Volt(4) + Watt(6) 这样的禁止操作)
最佳答案
图书馆形式确实有一种不那么冗长的方式, Boost.Units 将 SI 单位定义为类型安全类模板实例化。
关于C++:是否有更简洁的方式来表示自定义数字类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7674653/