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

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

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

我是写小程序的C++。我处理多个文件的意义太大了。我坚持使用另一个文件中的类。我做了一个简单的测试项目来演示我的问题。我有3个文件。

testheader.h

代码语言:javascript
运行
复制
#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

代码语言:javascript
运行
复制
#include <string>
#include <iostream>

using namespace std;

class testheader {
    public:
    testheader(string name){
        cout << name << endl;
    }
    void write(){
        cout << "stuff" << endl;
    }
};

anotherfile.cpp

代码语言:javascript
运行
复制
#include <iostream>
#include "testheader.h"

using namespace std;

int main () {
    cout << "testing" << endl;
    testheader test("mine");
    test.write();
    return 0;
}

我使用g++和下面的命令在Linux中编译了它们。

代码语言:javascript
运行
复制
g++ -std=c++11 testheader.cpp anotherfile.cpp testheader.h -o another

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

测试

我所期待的是输出

测试我的东西

似乎我的类对象"test“正在编译为null。我不确定是我的头文件还是文件链接不正确。当testheader对象在main中创建时,它显然没有像预期的那样调用testheader.cpp中的构造函数。你能帮帮菜鸟吗?

谢谢,Noob

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

https://stackoverflow.com/questions/50710256

复制
相关文章

相似问题

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