簡體   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