C++ 有没有一种方法可以;继承;基类型,如int?
我有几个类似的结构:C++ 有没有一种方法可以;继承;基类型,如int?,c++,C++,我有几个类似的结构: struct Time64 { int64_t Milliseconds; Time64 operator+(const Time64& right) { return Time64(Milliseconds + right.Milliseconds); } ... blah blah all the arithmetic operators for calculating with Time64 and int64
struct Time64 {
int64_t Milliseconds;
Time64 operator+(const Time64& right) {
return Time64(Milliseconds + right.Milliseconds);
}
... blah blah all the arithmetic operators for calculating with Time64 and int64_t which is assumed to represent milliseconds
std::string Parse() {
fancy text output
}
}
现在我需要添加更多的内容。。本质上,它们只是对任何基类的解释,并定义所有运算符,对它们来说,这样做真的很乏味。解释函数(例如示例中的“parse”)非常重要,因为我在整个UI中都使用它们。我知道我可以像这样创建独立的解释函数
std::string InterpretInt64AsTimeString(const Int64_t input) {...}
但将这些函数称为类方法会使代码看起来更好
如果有办法“typedef Int64_t Time64”,然后通过添加一些方法来扩展Time64“类”就好了
有什么方法比我现在所做的更容易实现我想做的吗?我想你想要的。不能从int
继承,因为int
不是类类型,但可以执行以下操作:
BOOST_STRONG_TYPEDEF(int64_t, Time64Base);
struct Time64 : Time64Base {
std::string Parse() { ... }
};
以下是如何在没有增压的情况下进行此操作: 您需要使您的结构隐式转换为底层类型,如CoffeeandCode所说。这是我们工作的一大部分
struct Time64{
int64_t毫秒;
运算符int64_t&({返回毫秒;}
};
int main(){
时间64 x;
x、 毫秒=0;
x++;
std::难道你正在走下坡路吗;底部是堆积如山的无用样板代码。为什么不使用std::chrono
?我想你需要的是隐式转换运算符。
struct Time64 {
int64_t Milliseconds;
operator int64_t &() { return Milliseconds; }
};
int main(){
Time64 x;
x.Milliseconds = 0;
x++;
std::cout << x << std::endl;
}