为什么这个简单的C++程序无法链接?我已尽可能密切地关注所有文章

问题描述 投票:0回答:1

我有一个由多个类组成的程序,其中许多类相互引用。因此,根据建议,我为每个原型创建一个原型作为头文件。任何需要另一个模块的模块都会获得适当的#include。文件编译但无法链接,我不明白为什么。这是一个简化到最少的示例。首先是一个原型,data.h:

#ifndef DATA_H
#define DATA_H

class Data {
    public:
        int get();
        void set(int);
        Data();
};

#endif

接下来是实现文件,data.cpp:

class Data {
    private:
        int content;

    public:
        int get() {
            return content;
        }

        void set(int value) {
            content = value;
        }

        Data() {}
};

最后是主程序,test.cpp:

#include "data.h"

int main(int argc, char* argv[]) {
  Data* data = new Data();
  data->set(5);
  int n = data->get();
  return 0;
};

我用

编译
g++ -c test.cpp data.cpp

没有错误,所以我链接到

g++ test.o data.o

并导致以下错误:

/usr/bin/ld: test.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Data::Data()'
/usr/bin/ld: test.cpp:(.text+0x44): undefined reference to `Data::set(int)'
/usr/bin/ld: test.cpp:(.text+0x50): undefined reference to `Data::get()'
collect2: error: ld returned 1 exit status

任何人都可以解释我做错了什么吗?

c++ hyperlink
1个回答
0
投票

如果你想在同一个文件中包含类方法的定义和实现,你可以在 data.h 中包含以下代码:

#ifndef DATA_H
#define DATA_H

class Data {
    private:
        int content;

    public:
        int get() {
            return content;
        }

        void set(int value) {
            content = value;
        }

        Data() {}
};
#endif

如果您想将实现移至 cpp 文件(在此处阅读有关此概念的信息),您可以使用以下代码...

数据.h:

#ifndef DATA_H
#define DATA_H

class Data {
    public:
        int get();
        void set(int);
        Data();
};

#endif

数据.cpp

#include "data.h" // This one is important here

int Data::get() 
{
    return content;
}

void Data::set(int value) {
    content = value;
}

Data::Data() {
}

附注另外,由于 test.cpp 中的

Data* data
,您也有内存泄漏 - 谷歌或查看 this

© www.soinside.com 2019 - 2024. All rights reserved.