有没有这样的事情作为一个C#风格的扩展方法在C + +? [英] Is there such a thing as a C# style extension method in C++?
问题描述
我目前正在学习C ++,我遇到了一个简单的问题,将int转换为字符串。我使用下面的工具:
string IntToString(int Number)
{
stringstream Stream;
Stream<<数;
return Stream.str();
}
但是使用类似的东西会更加优雅:
int x = 5;
string y = x.toString();
但是如何添加 toString()
方法到内置类型
或者我缺少完全基本的东西?
我不会从basic_string / string派生任何类。这不是推荐,并且在字符串中没有方法是虚拟的,它没有虚拟析构函数(因此导出可能会在内存泄漏)。
/ p>
您可以创建一个静态类(只包含静态方法的类),以便将其保存在一个地方。使用方法重载int,float,double等。
class Converter {
private:
Converter (){}
public:
static string toString(int i){
...您的实现...
}
$ b b static string toString(float f){
... same but floatats。
}
.... other overloads ....
};
...你的代码中的其他地方....
string c = Converter :: toString(5);
I'm currently learning C++ and i run into the simple problem of converting an int to a string. I've worked around it using:
string IntToString(int Number)
{
stringstream Stream;
Stream << Number;
return Stream.str();
}
but though it would be more elegant to use something like:
int x = 5;
string y = x.toString();
but how do i add the toString()
method to a built in type?
or am i missing something totally fundamental?
I would not derive any class from basic_string/string. This is not recommended and no method in string is virtual, it does not have a virtual destructor (hence deriving could reault in memory leaks)
Make it pretty for yourself:
You could create a static class (class containing only static methods) in order keep it all in the one place. Use method overloading for int, float, double, etc.
class Converter {
private:
Converter() {}
public:
static string toString(int i) {
... your implementation ...
}
static string toString(float f) {
... same but floats.
}
.... other overloads ....
};
... somewhere else in your code ....
string c = Converter::toString(5);
这篇关于有没有这样的事情作为一个C#风格的扩展方法在C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!