为什么我不能在另一个文件中调用类的非默认构造函数?

时间:2016-01-16 01:15:46

标签: c++ c++11

我是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 个答案:

答案 0 :(得分:1)

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

  1. 您忘了编译Row.cpp
  2. 您忘了将Row.o链接到最终的可执行文件中。
  3. 如果您是从命令行进行编译,请确保同时编译main.cppRow.cpp。这应该解决问题!