2014-10-01 94 views
0

我想在C++中首次使用多個文件。這是我寫的文件。未定義的引用Class :: Class()和Class :: function()

文件#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我得到以下錯誤:

未定義的引用 '對話框::框(INT,INT,INT)'

未定義的引用 '對話框::體積()'

我想不通爲什麼。

+2

你是如何構建的程序?你鏈接*兩個*源文件? – 2014-10-01 12:43:57

+0

也許這會幫助你:http://stackoverflow.com/questions/14173217/c-calling-a-function-from-another-class – Matheno 2014-10-01 12:47:51

回答

1

您需要同時使用文件,如編譯:

$ g++ main.cpp Box.cpp 

我覺得你編譯如下:

$ g++ main.cpp 
相關問題