Hello all, the code below is a vector class which is a child of the STL vector class. The code below will generate an error when doing this in the main function:
Vec<double> d = 2*x,
since 2 can be understood as an integer or double. If I do the following:
Vec<double> d = 2.0*x
will be ok, since 2.0 is a double.
Can anyone tell me how can I fix my code, so that when one does any of the above two lines no error appears and of course the result is correct? That is, i want that this
Yes, I also have * overloaded as a member function in my full code (not shown above). In that case I can do x*2 or x*2.0 without problems ... I think because 2 is automatically converted to double. With the approach in the code shown above, I wanted to compute in the inverse order, that is: 2*x, this way I could do it in both ways, x*2 or 2*x.
1) I don't see why should I use explicit in the length constructor. can you explian more?
2) My full code has also other functions and i don't have problems with the heritage from std::vector class? can you explian what also could go wrong if i use std::vector as the parent class?
class Thing {
private:
std::string stuff;
public:
Thing();
explicit Thing(int);
Thing(std::string);
}
Thing::Thing() : stuff()
{
}
Thing::Thing(int data) {
//do stuff with int...
}
Thing::Thing(std::string data) {
//do stuff with string...
}
int main() {
int a = 0;
std::string b = "data";
Thing something; //works
Thing something2(a); //works
//Thing something3 = a; //does not work, the int constructor must be explicitly called like the above
Thing something4(b); //works
Thing something5 = b; //works, same as something4
return 0;
}
1)Now, my problem is twofold: I have to explicitly use 2.0*x and x*2.0. Is there any way that the code works fine independently if I use 2 or 2.0? Also, one point that it is important to me. This modified code works fine under MVS, but it won't work under GNU compiler. That is, if I use g++ main.cpp, it will produce an error because there is no *= that matches the overloaded operators in std::vector class. How can i make it so that it can also be built in the GNU compiler?
2) How can I overload (), so that I can use it as x(i) rather than x[i]? I tried to do it overlading () as a free function but the compiler complains that () must be a non-static member.
I see. Thanks. I am thinking in doing a wrapper to the std::vector (i have posted part of the code here: http://www.cplusplus.com/forum/general/13931/ ). What do you think is better? doing the above code or doing the wrapper?