对 Class::Class() 和 Class::function() 的未定义引用 [重复]

undefined reference to Class::Class() and Class::function() [duplicate]

提问人:Lucchini 提问时间:10/1/2014 最后编辑:CommunityLucchini 更新时间:10/1/2014 访问量:1085

问:

我第一次尝试在 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: 盒子.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++ 头文件 未定义引用

评论

2赞 Mike Seymour 10/1/2014
您是如何构建程序的?是否链接了两个源文件?
0赞 Matheno 10/1/2014
也许这会帮助你:stackoverflow.com/questions/14173217/......

答:

1赞 Ashwani 10/1/2014 #1

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

$ g++ main.cpp Box.cpp  

我认为你是这样编译的:

$ g++ main.cpp