O
olson_ord
Hi,
I am not exactly new to C++, but I have never done operator
overloading before.
I have some old code that tries to implement a Shift Register - but I
cannot seem to get it to work. Here's a simpler version of it.
-------------------- main.cpp---------------------------
# include <iostream>
# include <vector>
# include <cassert>
class ShiftRegister {
public:
ShiftRegister(unsigned size) : _reg(size) {
}
bool& operator[](unsigned ix) {
return _reg[ix];
}
const bool& operator[](unsigned ix) const {
return _reg[ix];
}
private:
std::vector<bool> _reg;
};
int main(int argc, char* argv[]) {
ShiftRegister sftreg(2);
}
------------------ end of main.cpp ----------------
The above contains two definitions of the subscript operator one
ordinary and one constant. Compiling this I get
1. For the ordinary or variable subscript operator
error: could not convert `std::vector<bool,
_Alloc>:perator[](unsigned int) [with _Alloc =
std::allocator<bool>](ix)'
to `bool&'
2. For the constant subscript operator
warning: returning reference to temporary
I think I am missing something here, but looking in books or on the
internet does not make me understand what I am doing wrong i.e. they
seem to be doing the same thing (but with arrays or pointers - not with
vectors.)
I hope someone has some ideas on how to get this to work.
Thanks a lot.
O.O.
I am not exactly new to C++, but I have never done operator
overloading before.
I have some old code that tries to implement a Shift Register - but I
cannot seem to get it to work. Here's a simpler version of it.
-------------------- main.cpp---------------------------
# include <iostream>
# include <vector>
# include <cassert>
class ShiftRegister {
public:
ShiftRegister(unsigned size) : _reg(size) {
}
bool& operator[](unsigned ix) {
return _reg[ix];
}
const bool& operator[](unsigned ix) const {
return _reg[ix];
}
private:
std::vector<bool> _reg;
};
int main(int argc, char* argv[]) {
ShiftRegister sftreg(2);
}
------------------ end of main.cpp ----------------
The above contains two definitions of the subscript operator one
ordinary and one constant. Compiling this I get
1. For the ordinary or variable subscript operator
error: could not convert `std::vector<bool,
_Alloc>:perator[](unsigned int) [with _Alloc =
std::allocator<bool>](ix)'
to `bool&'
2. For the constant subscript operator
warning: returning reference to temporary
I think I am missing something here, but looking in books or on the
internet does not make me understand what I am doing wrong i.e. they
seem to be doing the same thing (but with arrays or pointers - not with
vectors.)
I hope someone has some ideas on how to get this to work.
Thanks a lot.
O.O.