我正在编写一些逻辑来做一些日志记录,有一堆 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
关于c++ - 可以是 char*、long 或 int 的函数参数。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666990/