2016-01-16 39 views
1

我对C++相当陌生。我已经开始编写一个名为Row的类,并且我试图调用一个非默认构造函数来在单独的main.cpp文件中创建一个行对象,但是我不断收到一个我不明白的错误。任何人都可以向我解释我做错了什么吗?为什么我不能在另一个文件中调用一个类的非默认构造函数?

这里是我的三个文件:

Row.h

#ifndef ROW_H 
#define ROW_H 
#include<vector> 
#include<iostream> 

class Row { 
    std::vector<int> row; 
public: 
    // constructor 
    Row(std::vector<int> row); 
}; 

#endif 

Row.cpp

#include<vector> 
#include<iostream> 
#include "Row.h" 

// constructor 
Row::Row(std::vector<int> row_arg) { 
    row = row_arg; 
} 

的main.cpp

#include<vector> 
#include<iostream> 
#include "Row.h" 
using namespace std; 

int main() { 
    vector<int> v = {1, 2, 3, 4}; 
    Row row(v); 
    return 0; 
} 

我收到在尝试错误编译main.cpp是这样的:

/tmp/ccJvGzEW.o:pascal_classes.cpp:(.text+0x71): undefined reference to `Row::Row(std::vector<int, std::allocator<int> >)' 
/tmp/ccJvGzEW.o:pascal_classes.cpp:(.text+0x71): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Row::Row(std::vector<int, std::allocator<int> >)' 
collect2: error: ld returned 1 exit status 

回答

1

这看起来像一个链接错误,而不是一个编译器错误,我的猜测是,你得到这个错误,因为无论

  1. 你忘了编译Row.cpp,或
  2. 你忘了将Row.o链接到最终的可执行文件中。

如果您从命令行进行编译,请确保编译main.cppRow.cpp。这应该可以解决问题!

+0

完全做到了。我没有意识到我必须编译两个.cpp文件。谢谢! – CJH

相关问题