So in my Matrix class I've used some weird syntax in this post in order to use the class as a 2D array. However marking the second overload as const just tells me it expected a ';'.
#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;
}
Is there any way for me to fix this so const Matrix instances can use the overload?
The correct syntax is
const float (&operator[](unsigned int index) const) [Columns]
You could get this by starting with operator[](unsigned int index) const
, and then adding the result type around it, if you're into that sort of thing.
But why make life difficult?
Use a type alias.
using Row = float[Columns];
Row& operator[](unsigned int index);
const Row& operator[](unsigned int index) const;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.