我现在应该得到这个,但我还没有得到它.问题是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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:嗯,我花了一些时间再次阅读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)
Run Code Online (Sandbox Code Playgroud)
摆脱int&Foo :: operator []摆脱了这个错误.我知道我可以创建一个新的访问器来将更改应用到chars_,但我想我会更新它并找出我想要做的事情是否可行.
你operator[]是非常规的.在您的赋值运算符中,为什么不直接访问rhv.chars_?
例如
Foo& Foo::operator=(const Foo &rhv) {
_size = rhv._size;
_chars = rhv._chars;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
681 次 |
| 最近记录: |