c++ - 如何运行这个简单的 C++ 程序?

标签 c++

我是 C++ 初学者,正在尝试运行一些入门代码。我有以下文件,

myTest.h
////////

#ifndef __myTest_h__
#define __myTest_h__

#include <string>

using std::string;

class myTest{

public:    
    int main(int, char const**);
}; 

#endif // __myArray_h__ 



myTest.cpp
//////////


#include<iostream>
#include<string>
#include "myTest.h"
using namespace std;



int myTest::main(int argc, char const *argv[])
{

    std::cout<< "Hello World/n";
    return 0;
}

当我尝试使用命令 g++ myTest.cpp -o myTest.out 从 Mac OS 的终端运行时,我在终端中收到以下错误,

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

C++入门如何改代码?我可以使用命令 -v 提供更多信息,如果需要,请告诉我。

最佳答案

与 Java 或 C# 不同,您不能在类中拥有 main 函数,它必须是全局非成员函数。


你可以创建一个非常简单的 main 函数,然后调用你的成员函数 main 函数:

int main(int argc, char* argv[])
{
    myTest myTestObject;
    return myTestObject.main(argc, argv);
}

请注意,我需要创建一个 myTest 类的实例,这是因为 myTest::main 函数不是 static .如果你让它成为static,比如

class myTest
{
public:
    static int main(int, char *[]);
    ...
};

那么您的非成员 main 函数可能如下所示:

int main(int argc, char* argv[])
{
    return myTest::main(argc, argv);
}

关于c++ - 如何运行这个简单的 C++ 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38100123/

相关文章:

c++ - 如何正确退出可能正在等待 std::condition_variable 的 std::thread?

c++ - C++代码中的异常安全

c++ - 使用std::sort时如何理解此结果?

python - 导出 Python 的 C++ 类

c++ clock_gettime()溢出了吗?

c++ - 分析帖子请求

c++ - 使用虚拟保护方法继承

c++ - "??*"C++转义序列

c++ - 显式释放底层 C++ iostream 的内存

c++ - 保留有关访问状态的信息的想法