Lin*_*uck 1 c++ header class file
我通过编写小程序是 C++。我也是处理多个文件的重点。我一直坚持使用另一个文件中的类。我做了一个简单的测试项目来演示我的问题。我有3个文件。
测试头文件
#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
Run Code Online (Sandbox Code Playgroud)
测试头文件
#include <string>
#include <iostream>
using namespace std;
class testheader {
    public:
    testheader(string name){
        cout << name << endl;
    }
    void write(){
        cout << "stuff" << endl;
    }
};
Run Code Online (Sandbox Code Playgroud)
另一个文件.cpp
#include <iostream>
#include "testheader.h"
using namespace std;
int main () {
    cout << "testing" << endl;
    testheader test("mine");
    test.write();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在 Linux 中使用 g++ 和命令编译它们
g++ -std=c++11 testheader.cpp anotherfile.cpp testheader.h -o another
Run Code Online (Sandbox Code Playgroud)
当我运行“另一个”可执行文件时,输出是
测试
我期待的是输出
测试我的东西
似乎我的类对象“test”正在编译为 null。我不确定这是我的标题还是文件链接不正确。当在 main 中创建 testheader 对象时,它显然没有按预期调用 testheader.cpp 中的构造函数。你能帮个菜鸟吗?
谢谢,菜鸟
在 testheader.h
testheader(std::string name){}
Run Code Online (Sandbox Code Playgroud)
定义(声明和实现)一个什么都不做的函数,而不是简单地声明它以便它可以在其他地方实现。这就是所谓的而不是印刷。你要
testheader(std::string name);
Run Code Online (Sandbox Code Playgroud)
现在main可以看到该函数存在并且链接器将查找它(一旦修复了第二和第三个,在 testheader.cpp 中找到它。
g++ -std=c++11 testheader.cpp anotherfile.cpp testheader.h -o another
Run Code Online (Sandbox Code Playgroud)
不要编译头文件。头文件的副本包含在它的所有文件中#include。只编译实现文件,所以
g++ -std=c++11 testheader.cpp anotherfile.cpp -o another
Run Code Online (Sandbox Code Playgroud)
的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;
}
Run Code Online (Sandbox Code Playgroud)
旁注:__testheader_H_INCLUDED__是非法标识符。关于如何/在何处使用下划线的其他规则(在 C++ 标识符中使用下划线的规则是什么?)永远不要在代码中的任何位置连续放置两个下划线。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           3660 次  |  
        
|   最近记录:  |