C++不能使用其他文件中的类

C++ can't use class from another file

本文关键字:文件 其他 不能 C++      更新时间:2023-10-16

我C++编写小程序。我也是处理多个文件的重点。我坚持使用另一个文件中的类。我做了一个简单的测试项目来演示我的问题。我有 3 个文件。

testheader.h

#ifndef __testheader_H_INCLUDED__   // if Node.h hasn't been included yet...
#define __testheader_H_INCLUDED__   //   #define this so the compiler knows it has been included
#include <string>
#include <iostream>
class testheader { 
public:
testheader(std::string name){}
void write(){}
};
#endif

测试标头.cpp

#include <string>
#include <iostream>
using namespace std;
class testheader {
public:
testheader(string name){
cout << name << endl;
}
void write(){
cout << "stuff" << endl;
}
};

另一个文件.cpp

#include <iostream>
#include "testheader.h"
using namespace std;
int main () {
cout << "testing" << endl;
testheader test("mine");
test.write();
return 0;
}

我在 Linux 中使用 g++ 和命令编译它们

g++ -std=c++11 testheader.cpp anotherfile.cpp testheader.h -o another

当我运行"另一个"可执行文件时,输出是

测试

我期待的是输出

测试 矿山 东西

似乎我的类对象"测试"正在编译为空。我不确定是我的标题还是文件未正确链接。当在 main 中创建 testheader 对象时.cpp它显然没有像预期的那样调用 testheader 中的构造函数。你能帮助一个菜鸟吗?

谢谢 菜鸟

主事件

在测试头.h 中

testheader(std::string name){}

定义(声明和实现(一个不执行任何操作的函数,而不是简单地声明它,以便它可以在其他地方实现。这就是所谓的而不是打印。你想要

testheader(std::string name);

现在main可以看到该函数存在,链接器将查找它(一旦修复了第二个和第三个,请在testheader中找到它.cpp。

下一个

g++ -std=c++11 testheader.cpp anotherfile.cpp testheader.h -o another

不要编译头文件。头文件的副本包含在#include它的所有文件中。仅编译实现文件,因此

g++ -std=c++11 testheader.cpp anotherfile.cpp -o another

第三步:获利!

testheader在testheader.h中定义。 只有静态成员的函数和存储的实现需要位于 testheader.cpp 中。

示例测试标头.cpp:

#include <string>
#include <iostream>
#include "testheader.h" // so it knows what testheader looks like
using namespace std;
testheader::testheader(string name)
{
cout << name << endl;
}
void testheader::write()
{
cout << "stuff" << endl;
}

旁注:__testheader_H_INCLUDED__是非法标识符。在关于如何/在哪里使用下划线的其他规则中(关于在C++标识符中使用下划线的规则是什么?(永远不要在代码中的任何位置连续放置两个下划线。