c++ - 对 Class::Class() 和 Class::function() 的 undefined reference

标签 c++ header-files undefined-reference

<分区>

我第一次尝试在 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 时出现以下错误:

undefined reference to 'Box::Box(int, int, int)'

undefined reference to 'Box::volume()'

我不知道为什么。

最佳答案

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

$ g++ main.cpp Box.cpp  

我想你是这样编译的:

$ g++ main.cpp

关于c++ - 对 Class::Class() 和 Class::function() 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26141641/

相关文章:

c++ - 在 Win32 错误中使用整数

c++ - 在 Windows 中更改原始波形数据的音高

C++ #elif 指令被丢弃

c++ - 为我的 C++ 静态库创建接口(interface)

c++ - autotools undefined reference 错误

具有聚合初始化的 C++ 常量匿名实例

c - 带有原始数据的头文件的目的是什么?

C++ 使用带有在头文件中定义的全局变量的 C 库

c - C 中 undefined reference

c - GCC 程序未定义对函数的引用(多个文件夹)