【问题标题】:Why could I not find the class in preprocessor?为什么我在预处理器中找不到类?
【发布时间】:2013-06-27 03:09:42
【问题描述】:

这可能很幼稚,但是我对cpp的预处理器感到很困惑: 我定义了一个头文件——Node.h:

#ifndef NODE_H_
#define NODE_H_

#include<iostream>
class Node{
    friend std::ostream &operator<<(std::ostream &os, const Node & n);
    public:
        Node(const int i = -1);
    private:
        Node * next;
        int value;
    friend class List;

};
#endif

然后我在Node.cpp中定义了方法:

#include "Node.h"
using namespace std;

Node::Node(const int i):value(i), next(NULL){}

ostream& operator <<(ostream & os, const Node& n){
    return os<<"value : "<<n.value<<endl;
}

最后,我有一个 test.cpp 文件来检查预处理器:

#include "Node.h"
//#include <iostream>
using namespace std;

int main(){
    Node * n = new Node;
    cout<<*n;
}

但是,当我尝试使用 gcc 编译时,出现以下错误:

/home/xuan/lib/singleLinkedList/test.cpp:6:‘Node::Node(int)’未定义引用

【问题讨论】:

  • 建议:const int 在这里没有意义,使用Node(int i)

标签: c++ c-preprocessor


【解决方案1】:

鉴于你的文件,当我运行时:

$ g++ test.cpp
/tmp/ccM7wRNZ.o:test.cpp:(.text+0x2c): undefined reference to `Node::Node(int)'
/tmp/ccM7wRNZ.o:test.cpp:(.text+0x44): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Node const&)'
/usr/lib/gcc/i686-pc-cygwin/4.5.3/../../../../i686-pc-cygwin/bin/ld: /tmp/ccM7wRNZ.o: bad reloc address 0x0 in section `.ctors'
collect2: ld returned 1 exit status

...但是如果我运行:

Simon@R12043 ~/dev/test/cpp
$ g++ test.cpp node.cpp

Simon@R12043 ~/dev/test/cpp
$

因此,我认为您没有将node.cpp 包含在要链接到项目中的文件中。也就是说,链接器没有找到Node 类。

【讨论】:

  • 别觉得自己很蠢——我记得几年前我在学习 Java 时花了 解决这类问题。通过发布一个简洁但完整的示例,您让我很容易找到您的问题(因此我对您的问题投了赞成票)。如果我的回答帮助您解决了您的问题,请将其勾选为已接受。祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 2022-09-27
  • 2015-04-26
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 2013-10-17
相关资源
最近更新 更多