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

Why can't I call a class's non-default constructor in another file?

本文关键字:默认 构造函数 调用 不能 另一个 文件 为什么      更新时间:2023-10-16

我对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

行.cpp

#include<vector>
#include<iostream>
#include "Row.h"
// constructor
Row::Row(std::vector<int> row_arg) {
    row = row_arg;
}

主.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. 您忘记编译Row.cpp,或者
  2. 您忘记将Row.o链接到最终的可执行文件中。

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