Re: operator overloading ==
A wrote:
I am writing a "vector" class. I know about the STL but I prefer to
use this as I use this to create a "matrix" class later. I read that
using the inbuilt STL to create a matrix is not the best way to do it.
Ahem, no? I mean such a general statement is not generally true. How and if
you can use std::vector depends on how your matrix class eventually looks
like. What I can say is that generally the standard-supplied classes are of
better quality than those you roll yourself.
template <class T>
class vec {
private:
int length;
T *v;
public:
vec();
explicit vec(int n);
vec(const T &a, int n);
vec(const T *a, int n);
vec(const vec &cpy);
vec & operator=(const vec &equate);
vec & operator=(const T &a);
inline T & operator[](const int i);
inline const T & operator[](const int i) const;
inline int size() const;
~vec();
};
First thing I see which strikes me as wrong is the use of 'int' for the
length, as opposed to size_t. Further, there are no iterators, no reserve
memberfunction or generally functions to change the size or insert/delete
elements. Using this is IMHO not a better replacement for std::vector.
Now, I want to overload the operator == [...]
member function:
vec<bool> operator==(const T &a) const;
[...]
This works great, but I would like to return the reference instead of
the whole vector and would like to know how to do it. I am unable to
make use of the "this" pointer as I am returning a "local vector".
Why do you want that? If you think about speed, profile that first and then
apply MOJO[1] if necessary. Otherwise, you can't. What you could do is to
pass in a reference to the output vector, but then you can't use
operator==, that only works in a function.
if(v[i] == a) {
tmp[i] = true;
}
This boils down to
if(/boolean expression/ == true)
tmp[i] = true;
The else branch is not present, but you have the initialisation of 'tmp'
with 'false' earlier on. Safe yourself that trouble and simply do:
tmp[i] = v[i]==a;
Uli
[1] Search the web for "C++ MOJO".
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]