所以,我正在开发一个项目,并且该项目中有两个文件: main.cpp,矩阵.h
问题是我的代码在几个小时前似乎工作得很好,但现在却不行了
main.cpp:
#include <iostream>
#include "matrix.h"
#include <vector>
int main() {
Matrix f;
f.create(10, 1, {3, 4, 5, 6, 7, 8, 9});
}
矩阵.h:
#pragma once
#include <iostream>
#include <string>
#include <Windows.h>
#include <vector>
class Matrix {
public:
const size_t N;
bool ifMatrixCreated;
const char* NOTENOUGH = "The size of the array should match to the width*height elements";
std::vector<int> arr;
int w, h;
void create(int width, int height, const std::vector<int> a) {
w = width;
h = height;
if (a.size() != width * height) {
ifMatrixCreated = false;
std::cout << "bello";
}
else {
ifMatrixCreated = true;
arr = a;
std::cout << "hello";
}
}
};
当我编译时,它会生成此错误(使用 VS2019):
Error C2280 | 'Matrix::Matrix(void)': attempting to reference a deleted function Matrix | Line 5
一直提示“Matrix 的默认构造函数无法被引用 - 它是一个已删除的函数”
你能帮忙解决这个错误吗?
提前致谢。
最佳答案
这是正确的工作示例。发生该错误是因为每个 const 数据成员都必须初始化。并且
The implicitly-declared or defaulted default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true:
- T has a const member without user-defined default constructor or a brace-or-equal initializer (since C++11).
#pragma once
#include <iostream>
#include <string>
//#include <Windows.h>
#include <vector>
class Matrix {
public:
//const size_t N;//this const data member must be initialised
const size_t N = 6;
bool ifMatrixCreated;
const char* NOTENOUGH = "The size of the array should match to the width*height elements";
std::vector<int> arr;
int w, h;
void create(int width, int height, const std::vector<int> a) {
w = width;
h = height;
if (a.size() != width * height) {
ifMatrixCreated = false;
std::cout << "bello";
}
else {
ifMatrixCreated = true;
arr = a;
std::cout << "hello";
}
}
};
关于c++ - 错误 C2280:Class::Class(void):尝试引用已删除的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69236089/