我只是想知道如何重載運算符[]來訪問一個類中的矩陣,並且我發現如何去那個here。 但是,我對此有個疑問:更換矩陣的哪種方法會更有效率?C++重載運算符[]效率
1:重載operator []:(從以前的鏈接提取的代碼)
class CMatrix {
public:
int rows, cols;
int **arr;
public:
int* operator[](int const y)
{
return &arr[0][y];
}
....
編輯:我過於依賴其他的例子:它應該以這種方式工作?
int* operator[](int const x)
{
return &arr[x];
}
2:使用一個 「正常」 的方法:
class CMatrix {
public:
int rows, cols;
int **arr;
public:
void changematrix(int i, int j, int n)
{
arr[i][j]=n;
}
...
編輯:於changematrix固定常數
1.這些甚至等價的代碼? 2.你正在從一個'const'函數改變狀態? – crashmstr
我會建議重載函數操作符而不是索引操作符。 – Codor
在繼續之前,請考慮您是否真的需要這種訪問。在很多情況下,簡單地重載operator()以訪問元素會更簡潔;這使得代碼更容易理解,使用簡單並且不需要這種解決方法。 – MatthiasB