我是写小程序的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(){}
};
#endiftestheader.cpp
#include <string>
#include <iostream>
using namespace std;
class testheader {
public:
testheader(string name){
cout << name << endl;
}
void write(){
cout << "stuff" << endl;
}
};anotherfile.cpp
#include <iostream>
#include "testheader.h"
using namespace std;
int main () {
cout << "testing" << endl;
testheader test("mine");
test.write();
return 0;
}我使用g++和下面的命令在Linux中编译了它们。
g++ -std=c++11 testheader.cpp anotherfile.cpp testheader.h -o another当我运行“另一个”可执行文件时,输出是
测试
我所期待的是输出
测试我的东西
似乎我的类对象"test“正在编译为null。我不确定是我的头文件还是文件链接不正确。当testheader对象在main中创建时,它显然没有像预期的那样调用testheader.cpp中的构造函数。你能帮帮菜鸟吗?
谢谢,Noob
https://stackoverflow.com/questions/50710256
复制相似问题