我現在應該知道這一點,但我還沒有得到它。麻煩的是,operator =的參數可能是非const的,但是它打破了std :: vector :: push_back,因爲它使得該項爲const,所以operator =必須接受一個const對象。那麼,我不確定我應該如何修改這個對象。常見問題
#include <vector>
#include <map>
#include <iostream>
using namespace std;
int font[] = {0, 31, 0, 31, 0, 31, 0, 31};
class Foo {
int size_;
std::map<int, int> chars_;
public:
Foo(int *font, int size);
unsigned int Size() const { return size_; }
void Add(int ch);
bool operator==(const Foo &rhv) const;
int &operator[](int i);
int const operator[](int i);
Foo operator=(const Foo &rhv);
};
Foo::Foo(int *font, int size) {
for(int i = 0; i < size; i++) {
chars_[size_++] = font[i];
}
}
bool Foo::operator==(const Foo &rhv) const {
if(Size() != rhv.Size()) return false;
/*for(int i = 0; i < Size(); i++) {
if (chars_[i] != *rhv[i])
return false;
}*/
return true;
}
int &Foo::operator[](int i) {
return chars_[i];
}
int const Foo::operator[](int i) {
return chars_[i];
}
Foo Foo::operator=(const Foo &rhv) {
if(this == &rhv) return *this;
for(unsigned int i = 0; i < rhv.Size(); i++) {
//Add(*rhv[i]);
//chars_[size_++] = rhv[i];
}
return *this;
}
void Foo::Add(int ch) {
chars_[size_++] = ch;
}
int main()
{
vector<Foo> baz;
Foo bar = Foo(font, 8);
baz.push_back(bar);
}
編輯:嗯,我花了一些時間再讀一遍const。我甚至想做甚麼?我要問的原因是因爲這樣的句子: 如果它沒有使用const限定符進行編譯,並且你正在返回一個引用或指向某個可能是該對象一部分的指針,那麼你的設計就不好。
我考慮到了這一點,並避免在const方法中返回引用。這產生了這個錯誤:
test.cpp:18: error: 'const int Foo::operator[](int)' cannot be overloaded
test.cpp:17: error: with 'int& Foo::operator[](int)'
test.cpp:41: error: prototype for 'const int Foo::operator[](int)' does not match any in class 'Foo'
test.cpp:37: error: candidate is: int& Foo::operator[](int)
擺脫INT &富:: operator []的擺脫那個錯誤的。我知道我可以創建一個新的訪問器來將更改應用於chars_,但我想我會更新這個,並且發現我想要做什麼是可能的。
int operator [](int i)const;將無法工作。我發現了一個可行的解決方案。 'map Foo :: Chars()const;'我可以索引返回 –
Scott
2009-10-17 18:55:37
我沒有解釋爲什麼只改變那一行就行不通。我爲你添加了一個完整的代碼示例。如果您真的有興趣瞭解發生了什麼問題,我強烈建議您閱讀我指出的鏈接。 – cdiggins 2009-10-17 19:05:42
我知道我需要返回一個const。無論如何,今天我有我的份額。獎金:我學到了什麼。告別指針。 – Scott 2009-10-17 19:12:24