c++ - 可以是 char*、long 或 int 的函数参数。是否可以?

标签 c++ casting void-pointers

我正在编写一些逻辑来做一些日志记录,有一堆 C++ 与 C 混合,因为这个库的大部分都是 p/Invoked。我已经设法编写了一个记录消息和可选参数的函数:

void writeToLog(char* message, char* arg) {
    std::ofstream file;
    file.open(fullpath, std::ios::in | std::ios::app);
    if (file.is_open()) {
        std::string fullMessage = getCurrentDateTime();
        fullMessage.append(message);
        if (arg != 0)
            fullMessage.append(arg);
        fullMessage.append("\n");
        const char* pcMessage = fullMessage.c_str();
        file << pcMessage;
        std::cout << pcMessage;
    }
    file.close();
}

然而它只需要 char* 作为参数,但我想将它们与 int 和 long 一起使用......我试过:

void writeToLog(char* message, void* arg) {
    std::ofstream file;
    file.open(fullpath, std::ios::in | std::ios::app);
    if (file.is_open()) {
        std::string fullMessage = getCurrentDateTime();
        fullMessage.append(message);
        if (arg != 0)
            fullMessage.append((char*)&arg);
        fullMessage.append("\n");
        const char* pcMessage = fullMessage.c_str();
        file << pcMessage;
        std::cout << pcMessage;
    }
    file.close();
}

但无论数据类型如何,它都会打印/写入乱码。请指出您认为合适的任何其他错误,我对 C/C++ 有点菜鸟。

最佳答案

您可以通过两种方式解决此问题。第一种方法是重载函数。这意味着您将一遍又一遍地编写相同的函数,只是使用不同的类型作为参数。 示例

#include <iostream>
using namespace std;

class printData {
public:
  void print(int i) {
     cout << "Printing int: " << i << endl;
  }

  void print(double  f) {
     cout << "Printing float: " << f << endl;
  }

  void print(char* c) {
     cout << "Printing character: " << c << endl;
  }
};

int main(void) {
 printData pd;

 // Call print to print integer
 pd.print(5);

 // Call print to print float
 pd.print(500.263);

 // Call print to print character
 pd.print("Hello C++");

 return 0;
}

此代码打印:

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

第二个选项是使用模板。基本上,你会做

template<class T>
void writeToLog(char* message, T arg){
   //continue to write code here without assuming anything about the type of arg
}

重载函数链接:https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm

模板链接:http://www.cplusplus.com/doc/oldtutorial/templates/

关于c++ - 可以是 char*、long 或 int 的函数参数。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666990/

相关文章:

c++ - C++ 读取文件

c - 指针初始化以遍历数组

c - 为什么可以使用具有错误签名的比较函数调用 `qsort` 并且编译没有警告

Java "x += y"和 "x = x+y"产生不同的结果

c# - 使用 LINQ 时 VB TryCast 和 C# "as"运算符的区别

c# - 为 Serilog 创建一个包装器

C - 动态地将 void 指针转换为结构

java - 整数域到定域映射数组的应用与实现

c++ - Qt 将信号连接到槽

c++ - 是否可以有一个变量,该变量是对具有不同类标识符的模板类的引用?