在c++类中保存函数

Saving functions in a class C++

本文关键字:保存 函数 c++      更新时间:2023-10-16

我是个十足的新手。

我已经创建了int到string和string到int转换的函数。

我想保存它们以便在任何程序中使用,我可以将它们命名为#include <iostream>

我是否可以通过创建一个类(然后没有私有成员变量)来实现这一点?

,如果我做它作为一个类,我如何使用函数而不创建对象?

基本上我想创建我自己的cmath或string之类的东西但我甚至不知道该叫什么来找出如何创建它

如果你只有简单的函数,你可以把它们放在一个命名空间中,它也像一个容器,然后把它们放在一个单独的cpp文件中,并创建一个包含原型的.h文件。

。E for mymath.h:

#ifndef MYMATH_H
#define MYMATH_H
namespace mymath
{
     int dosomething(int y);
}
#endif

和mymath.cpp:

#include "mymath.h"
int mymath::dosomething(int y)
{
}

然后,当你想使用它,你包括你的#include "mymath.h"文件和链接cpp到你的项目。

mystring.hpp

#ifndef MYSTRING_HPP
#define MYSTRING_HPP
#include <string>
namespace n_mystring
{
    std::string & IntToString( int Int );
    int StringToInt( std::string & String );
}
#endif

mystring.cpp

#include "mystring.hpp"
std::string & n_mystring::IntToString( int Int ) {
    //.... implementation
};
int n_mystring::StringToInt( std::string & String ) {
    //.... implementation
};
#include <iostream>
class Tools {
    public :
      void static sneeze ();
};
void Tools::sneeze ()
{
    std::cout << "atchoum";
}

int main () {
    Tools::sneeze(); // atchoum
}