将包含主函数的 C 程序包装到 C++ class,
Wrapping a C program that contains a main function into a C++ class,
我最近被要求将包含主函数的 C 程序包装到 C++ class 中,但我没有看到有效执行此操作的一般方法。
比如我的C程序是
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char * argv[]) {
int i, sum = 0;
if (argc != 3) {
printf("Two numbers are needed.\n");
exit(1);
}
printf("The sum is :%d \n ", atoi(argv[1])+atoi(argv[2]));
}
如何将这个主要函数包装到 C++ 中 class?我模糊的想法是用C++构造函数来模拟main的argc和argv,但是我不知道怎么做。你帮忙吗?
没那么难。只需将转换委托给 main()
函数,并传递正确的值:
SumComputer computer(atoi(argv[1]), atoi(argv[2]));
printf("The sum is :%d \n ", computer.sum());
你有一个 class 和一个像 SumComputer(const int a, const int b)
这样的构造函数和一个 int sum() const
函数。
您还可以拥有一个具有简单构造函数和更复杂 sum()
函数的对象,甚至可能使用 varargs.
大概是这样的?
class program {
public:
int main(int argc, char *argv[]) {
int i, sum = 0;
if (argc != 3) {
printf("Two numbers are needed.\n");
exit(1);
}
printf("The sum is :%d \n ", atoi(argv[1])+atoi(argv[2]));
return 0; // WE MUST DO THIS NOW!
}
};
// actual main for testing
int main(int argc, char **argv)
{
program p;
return p.main(argc, argv);
}
我们可以让构造函数成为主函数,但这似乎是个糟糕的主意;如果我们将任何内容放入 program
class,主函数可能希望在调用之前完成其构造。
我最近被要求将包含主函数的 C 程序包装到 C++ class 中,但我没有看到有效执行此操作的一般方法。
比如我的C程序是
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char * argv[]) {
int i, sum = 0;
if (argc != 3) {
printf("Two numbers are needed.\n");
exit(1);
}
printf("The sum is :%d \n ", atoi(argv[1])+atoi(argv[2]));
}
如何将这个主要函数包装到 C++ 中 class?我模糊的想法是用C++构造函数来模拟main的argc和argv,但是我不知道怎么做。你帮忙吗?
没那么难。只需将转换委托给 main()
函数,并传递正确的值:
SumComputer computer(atoi(argv[1]), atoi(argv[2]));
printf("The sum is :%d \n ", computer.sum());
你有一个 class 和一个像 SumComputer(const int a, const int b)
这样的构造函数和一个 int sum() const
函数。
您还可以拥有一个具有简单构造函数和更复杂 sum()
函数的对象,甚至可能使用 varargs.
大概是这样的?
class program {
public:
int main(int argc, char *argv[]) {
int i, sum = 0;
if (argc != 3) {
printf("Two numbers are needed.\n");
exit(1);
}
printf("The sum is :%d \n ", atoi(argv[1])+atoi(argv[2]));
return 0; // WE MUST DO THIS NOW!
}
};
// actual main for testing
int main(int argc, char **argv)
{
program p;
return p.main(argc, argv);
}
我们可以让构造函数成为主函数,但这似乎是个糟糕的主意;如果我们将任何内容放入 program
class,主函数可能希望在调用之前完成其构造。