C++ 不能使用另一个文件中的类

标签 c++ file class header

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

测试头.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

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

测试

我期待的是输出

测试 矿 东西

看来我的类对象“test”正在编译为 null。我不确定这是我的标题还是文件链接不正确。当在 main 中创建 testheader 对象时,它显然没有按预期调用 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 中。

示例 testheader.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__ 是非法标识符。在关于如何/在何处使用下划线 (What are the rules about using an underscore in a C++ identifier?) 的其他规则中,切勿在代码中的任何位置连续放置两个下划线。

关于C++ 不能使用另一个文件中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50710256/

相关文章:

c++ - 类构造函数中的模板和使用(#define)

java - 比较静态类中使用的参数

c++ - 即使我不执行动态分配,Valgrind 也会报告映射中的内存泄漏

c++ - DynamicArray of struct - 添加元素而不创建结构变量/对象

c++ - 大括号初始化函数指针数组: invalid conversion from 'void (*(*)())()' to 'void (*)()'

macos - 将所有文件递归地从子文件夹移动到父文件夹

c - 用c逐行写入文件

c# - VisualBasic.Net 与 Visual C#

C++ 返回临时对象的问题

python - 文件在进程中使用时自动关闭