【发布时间】: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()'的未定义引用
我不知道为什么。
【问题讨论】:
-
你是如何构建程序的?您是否正在链接两个源文件?
-
也许这会对你有所帮助:stackoverflow.com/questions/14173217/…
标签: c++ header-files undefined-reference