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