【问题标题】:undefined reference to Class::Class() and Class::function() [duplicate]对 Class::Class() 和 Class::function() 的未定义引用 [重复]
【发布时间】:2014-10-01 12:41:47
【问题描述】:

我第一次尝试在 C++ 中使用多个文件。这是我写的文件。

文件 #1:Box.hpp

#ifndef BOX_HPP
#define BOX_HPP

class Box
{
    private:
        int length;
        int width;
        int height;
    
        Box() {}

    public:
        Box(int _length, int _width, int _height);

        void set_dimensions(int _length, int _width, int _height);
        int volume();
 };

 #endif

文件 #2:Box.cpp

#include "Box.hpp"

Box::Box(int _length, int _width, int _height)
{
    set_dimensions(_length, _width, _height);
}

void Box::set_dimensions(int _length, int _width, int _height)
{
    length = _length;
    width = _width;
    height = _height;
}

int Box::volume()
{
    return length*width*height;
}

文件#3:main.cpp

#include "Box.hpp"
#include <iostream>

int main()
{
    Box box1 = Box(1,2,3);
    std::cout << box1.volume() << std::endl;
    return 0;
}

当我尝试运行 main.cpp 时,出现以下错误:

对'Box::Box(int, int, int)'的未定义引用

对'Box::volume()'的未定义引用

我不知道为什么。

【问题讨论】:

标签: c++ header-files undefined-reference


【解决方案1】:

您需要使用这两个文件进行编译,例如:

$ g++ main.cpp Box.cpp  

我认为你是这样编译的:

$ g++ main.cpp

【讨论】:

    猜你喜欢
    • 2012-09-16
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多