为什么我不能在另一个文件中调用类的非默认构造函数?
Why can't I call a class's non-default constructor in another file?
我对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
这看起来像是链接器错误,而不是编译器错误,我的猜测是你得到这个错误,因为要么
- 您忘记编译
Row.cpp
,或者 - 您忘记将
Row.o
链接到最终的可执行文件中。
如果从命令行进行编译,请确保同时编译 main.cpp
和 Row.cpp
。这应该可以解决问题!
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 为什么即使我调用参数化构造函数也会调用默认构造函数?
- 具有非默认构造函数的单例类
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 在C++中使用默认构造函数初始化对象的不同方法
- 在没有默认构造函数的情况下创建的派生对象
- 强制使用默认构造函数对成员进行未初始化的声明
- 使用默认构造函数初始化对象的不同方法
- 创建类类型的动态分配数组,其中类不得具有默认构造函数