【问题标题】:C++ can't use class from another fileC++ 不能使用另一个文件中的类
【发布时间】:2018-11-15 12:58:33
【问题描述】:

我是 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

testheader.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.cpp 应该包括testheader.h
  • testheader.cpp 不应该重新定义类。
  • 此外,您不能在标题中实现成员函数并在其他任何地方重新实现相同的成员。
  • 谢谢大家,我现在明白了。我没有意识到我在标题声明的末尾有括号,我不能两次使用这个类。
  • 不要使用以下划线开头的标识符。这些是为编译器、标准库或系统中的东西保留的。

标签: c++ file class header


【解决方案1】:

主赛事

在 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?) 永远不要在代码中的任何位置连续放置两个下划线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2017-11-16
    • 1970-01-01
    相关资源
    最近更新 更多