繁体   English   中英

无法将第二个下标运算符重载标记为 const

[英]Unable to mark a second subscript operator overload as const

因此,在我的矩阵 class 中,我在这篇文章中使用了一些奇怪的语法,以便将 class 用作二维数组。 然而,将第二个重载标记为 const 只是告诉我它需要一个';'。

#pragma once

#include <iostream>

using std::ostream;

struct Matrix {
public:
    
    Matrix(float identity = 0.0f) {
        for (int row = 0; row < 4; ++row)
            for (int column = 0; column < 4; ++column)
                matrix[row][column] = (row == column) ? identity : 0.0f;
    }
    
private:
    enum {
        Rows = 4,
        Columns = 4
    };
    
    float matrix[Rows][Columns];
public:
    float (&operator[](unsigned int index)) [Columns] {
        return matrix[index];
    }

    // won't let me mark it as const
    float (&operator[](unsigned int index)) [Columns] const // "expected a ';'" {
        return matrix[index];
    }
    
    friend ostream& operator<<(ostream& stream, const Matrix& matrix);
    
};

ostream& operator<<(ostream& stream, const Matrix& matrix) {
    for (int row = 0; row < 4; ++row) {
        for (int column = 0; column < 4; ++column) {
            stream << (column == 0 ? '[' : ' ');
            stream << matrix[row][column];
            stream << (column == 3 ? ']' : ' ');
        }
        stream << (row == 3 ? '\0' : '\n');
    }
    
    return stream;
}

我有什么办法可以解决这个问题,以便 const Matrix 实例可以使用重载?

正确的语法是

const float (&operator[](unsigned int index) const) [Columns] 

你可以从operator[](unsigned int index) const开始,然后在它周围添加结果类型,如果你喜欢这种事情的话。

但为什么要让生活变得困难呢?
使用类型别名。

using Row = float[Columns];
Row& operator[](unsigned int index);
const Row& operator[](unsigned int index) const;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM