c++ - 错误 C2280:Class::Class(void):尝试引用已删除的函数

标签 c++ visual-studio compiler-errors visual-studio-2019

所以,我正在开发一个项目,并且该项目中有两个文件: 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/

相关文章:

syntax - D FlipFlop VHDL的1Hz时钟

c++ - 由他们的 parent 绘制 QWidgets

c++ - 游戏开发,初学者的语言?

C++ 从另一个函数退出函数

c++ - 在 C++ 中添加静态库时的意外行为

c++ - 显然微不足道的函数调用中未处理的异常

c++ - 数组模板和内置数组类型之间有区别吗?

c++ - 如何改进 cvMat 中的像素排序?

c# - 如何在运行时更改当前资源管理器以切换语言?

c++ - 接口(interface)和实现 C++