c++ - ISO C++ 禁止声明没有类型的 ‘transpose’ [-fpermissive]

标签 c++

初级编码员在我的代码上遇到问题

我的 Matrix.h 文件

using namespace std;

class Matrix {
    private:

        vector<vector<int> > M;
        unsigned int ROWS;
        unsigned int COLS;
        bool operationIsValid(const Matrix &, const string&) const;

    public:

        //Constructors
        Matrix();
        Matrix(const string&);
        Matrix(int,int,int);

        //Accessors
        const Matrix transpose() const;
        ....   
};

我的 Matrix.cpp 文件

#include "Matrix.h"
....

using namespace std;

//Constructors
Matrix::Matrix() {
    vector<vector<int> > A(3, vector<int>(3, 0));
}


//Accessors
const Matrix::transpose() const{
    vector<vector<int> > B = A;
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3;j++) {
                A[i][j] = B[j][i];
            }
        }
}
.....

不太确定我做错了什么,所以任何反馈都会有所帮助! 第一次发帖,格式不对。

最佳答案

const Matrix transpose() const;   // declaration from header
const Matrix::transpose() const   // definition from cpp file

看起来您刚刚在 :: 中添加了内容。不幸的是,这意味着返回类型现在消失了,因为您已将它用于类说明符。

您需要定义为:

const Matrix Matrix::transpose() const { ... }
//    ^^^^^^
// (return type)

为什么您需要这样做的原因如下。当您声明类时(在 class classname { ... } 位内),您实际上不需要指定类名,因为它是隐式的。所以你会这样做:

class classname {
    void function(int param);
}

但是在声明的之外,您想要定义function 实际做什么的地方,您需要一种方法来告诉编译器它属于哪个类。所以你显式指定类:

void classname::function(int param) {
    weaveMagicWith(param);
}

在您的例子中,您使用了以下声明和定义(分隔开以便您可以看到等效位):

const Matrix transpose()         const;
const        Matrix::transpose() const { weaveMagic(); }

您*应该做的是将第一行中的 transpose() 替换为第二行中的 Matrix::transpose()。通过简单地添加 :: 而没有 类名,您已经有效地完全删除了返回类型,导致您的错误消息(我添加了强调位):

ISO C++ forbids declaration of 'transpose' with no [return] type


这与使用声明/定义对没有什么不同:

const int giveMeSeven();
const     giveMeSeven() { return 7; }

而第二行的正确变体是:

const int giveMeSeven() { return 7; } // with the 'int'

关于c++ - ISO C++ 禁止声明没有类型的 ‘transpose’ [-fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564948/

相关文章:

c++ - 如何在 C++ 中调用屏蔽函数?

c++:用随机字节填充缓冲区的最快方法

c++ - 专门对中的自定义访问器名称

c++ - 如何删除用户输入字符串末尾的空字符?

c++ - 此 vector 实现的可维护性问题

c++ - 使用 cin 对象进行输入验证并清除缓冲区 (c++)

c++ - 素数筛并不总能得到范围内的正确素数

c++ - 在 C++ 中,在 for 循环之外使用 "if"还是在 for 循环中使用 "if"效率更高

c++ - 在没有线程的情况下构建 Boost ASIO

c++ - 为什么 nvcc 无法使用 boost::spirit 编译 CUDA 文件?