首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C++不能使用其他文件中的类

C++不能使用其他文件中的类
EN

Stack Overflow用户
提问于 2018-06-06 07:27:52
回答 1查看 4.3K关注 0票数 1

我是写小程序的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;
    }
};

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-06 08:14:00

主要事件

在testheader.h中

testheader(std::string name){}

定义(声明和实现)一个什么也不做的函数,而不是简单地声明它,以便可以在其他地方实现它。这就是所谓的,而不是打印。你想要的

testheader(std::string name);

现在main可以看到函数存在,链接器将查找它(一旦修复了2和3,就在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?)的其他规则中,不要在代码中的任何地方将两个下划线放在一行中。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50710256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档