Re: overload "operator->"
On 2007-05-06 13:22, Jess wrote:
On May 4, 7:32 pm, James Kanze <james.ka...@gmail.com> wrote:
You can't change the syntax of C++ with operator overloading.
You can only extend it to support additional types.
By "extending", I guess I can't change a postfix to a prefix, or its
precedence?
Correct.
Can I change a member function to a non-member and vice
versa?
No, but for most(?) operators there's both a member and a non-member
version.
Can I change a unary operator to a binary or a binary to a
unary?
No.
Also, when ">>" and "<<" are used by iostream, are then member
operators of iostream or non-member functions?
Non-member, and that is how you should make the if you ever want to add
an operator<< to your class so that you can easily print it.
As far as I know the only operator that you have some freedom with is
the ()-operator, with which you can decide how many argument it takes,
all the others are quite fixed, in arity, precedence, postfix/prefix, etc.
b. why is b->f() the shorthand of
(b.operator->()) -> f()
Because that's what the standard says.
I see, it's the standard, though it doesn't look very obvious why
standard says it. :) When "->" is used with a pointer "p->b()" is
equivalent to (*p).b(). which doesn't show how we can use "->" with
user-defined class types.
The idea is that you should be able to make a class that acts just like
a pointer, and that requires that it works like that, take a look at
this code and compare my Pointer-class with a real pointer:
#include <string>
#include <iostream>
template<class T>
class Pointer
{
T* ptr_;
public:
Pointer(T* p) : ptr_(p) {}
T* operator->() { return ptr_; }
T& operator*() { return *ptr_; }
};
int main()
{
std::cout << "Using Pointer:\n";
Pointer<std::string> P(new std::string());
*P = "Hello";
P->append(" World\n");
std::cout << *P;
std::cout << "Using a std::string pointer:\n";
std::string* p = new std::string();
*p = "Hello";
p->append(" World\n");
std::cout << *p;
}
--
Erik Wikstr?m