自從片刻以來,有一件事讓我的大腦產生了困擾:我試圖根據返回類型重載[]運算符。這是我需要做的:返回類型的重載運算符[]返回類型
class A {
private:
double* data_;
int N_;
public:
A (N=0):N_(N){
data_ = new double[N];
}
~A {delete[] data_;}
double operator[] (const int i) {
return data_[i];
}
double* operator[] (const int i) {
return &data[i]; // for example; in fact here i need to return some block of data_
}
};
這段代碼不會編譯;這是我的問題。有人可以幫我解決這個問題嗎?
PS:我知道如何重載返回類型,例如正常功能:
int foo();
string foo();
我使用了一些技巧,我在這個論壇上閱讀。這樣:
struct func {
operator string() { return "1";}
operator int() { return 2; }
};
int main() {
int x = func(); // calls int version
string y = func(); // calls string version
double d = func(); // calls int version
cout << func() << endl; // calls int version
func(); // calls neither
}
謝謝。
「* PS:我知道如何在返回類型上重載正常函數,例如*」你確定嗎? – ildjarn
你在說什麼論壇? – Paulpro
您能告訴我們如何純粹重載類型嗎?我想很多人也想知道,因爲他們不知道... – PlasmaHH