using namespace std;
struct Vector
{
double x,y,z;
double &operator[](int i) { return (&x)[i]; }
};
void here_it_comes(const vector<Vector> &vertex)
{
double a = vertex[0][0]; // compile error
double b = const_cast<Vector&>(vertex[0])[0]; // no problem, but why
the need not to be const? I change it nowhere.
}
int main() { return 0; };
/*
1.cpp: In function 'void here_it_comes(const std::vector<Vector,
std::allocator<Vector> >&)':
1.cpp:14: error: passing 'const Vector' as 'this' argument of 'double&
Vector::operator[](int)' discards qualifiers
*/
'vertex' refers to a constant vector. That means that the operator[] of
it returns a reference to a *constant* Vector. Your Vector::operator[]
is non-const (since it is apparently designed to allow putting it on the
left side of the assignment operator). Declare another operator[] in
Vector, like so:
struct Vector
{
...
double operator[](int i) const { return (&x)[i]; }
and it's going to be OK.
> {
> double a = vertex[0][0]; // compile error
> double b = const_cast<Vector&>(vertex[0])[0]; // no problem, but why the
> need not to be const? I change it nowhere.
> }
>
>
> int main() { return 0; };
> /*
> 1.cpp: In function 'void here_it_comes(const std::vector<Vector,
> std::allocator<Vector> >&)':
> 1.cpp:14: error: passing 'const Vector' as 'this' argument of 'double&
> Vector::operator[](int)' discards qualifiers
> */
V
--
I do not respond to top-posted replies, please don't ask
> > #include <vector>
> > using namespace std;
> > struct Vector
> > {
> > double x,y,z;
> > double &operator[](int i) { return (&x)[i]; }
> > };
> > void here_it_comes(const vector<Vector> &vertex)
[...]
> Declare another operator[] in Vector,
> like so:
> struct Vector
> {
> ...
> double operator[](int i) const { return (&x)[i]; }
> and it's going to be OK.
But only if i is 0 (as it is in his test program). Otherwise,
he has undefined behavior.
--
James Kanze