C++不能使用其他文件中的类
C++ can't use class from another file
我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++标识符中使用下划线的规则是什么?(永远不要在代码中的任何位置连续放置两个下划线。
相关文章:
- 在其他文件中创建类时在 c++ 项目中不起作用
- 我应该将除 .cpp 以外的其他文件添加到 git 中吗?
- 如何在其他文件中使用函数
- C++ - 忽略并从其他文件获取数据
- CMake:在其他目录中找不到我的头文件
- 无法使用 CMake 从其他文件夹添加源文件
- 如何使用 C/C++ 和 system() 系统调用以外的其他方法在 Linux 中获取文件功能?
- 从文件中查找单词并替换到其他文件中
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 没有头文件如何使用c ++调用其他模块中的函数?
- 访问从 CPP 文件到其他头文件的静态变量
- 不能在其他文件中包含结构
- 无法打开包含文件'Graphics.hpp'没有这样的文件或目录,Visual Studio的其他包含不起作用
- 如何在 Linux 下使用 c++ 知道文件是否被其他进程使用?
- 使用函数打开文件,然后让其他函数利用该文件?
- 如何使用Winforms C#或C++.Net在不更改文件中其他内容的情况下修改jpg文件中的Orientation e
- 如何调试visual studio 2017生成的C++代码.android中的SO文件和其他第三方库
- 如何使用QXmlStreamReader解析包含对其他XML文件的引用的XML文件
- 如何在不受其他文件影响的情况下"by itself" Visual Studio 项目中运行C++文件?
- 如何将 cpp 文件中的静态函数公开给其他文件