"tom_usenet" <to********@hotmail.com> wrote in message
news:3e****************@news.easynet.co.uk
On Wed, 25 Jun 2003 00:20:23 +1000, "John Carson"
<do***********@datafast.net.au> wrote:
I don't know about the OP, but I read the following in Stroustrup
(TCPL, p. 287):
"An operator[]() must be a member function."
In Lippman's C++ Primer (p. 754), I read:
"A subscript operator must be defined as a class member function."
I also read in the C++ standard:
13.5.5 Subscripting
1 operator[] shall be a non-static member function with exactly one
parameter.
None of that stops operator[] from being a friend:
struct A
{
void operator[](int){}
};
struct B
{
friend void A::operator[](int);
};
Tom
You are right. Being a member function and being a friend are not mutually
exclusive.
I was thinking that being a friend was useless anyway for a subscript
operator because it could not take an object as an argument and hence could
not access any object's members. But of course there are other ways to make
a variable available to an operator besides passing the variable as an
argument, e.g.,
class B;
struct A
{
A();
~A();
B *pb;
int& operator[](int);
};
class B
{
friend int& A::operator[](int);
int array[10];
};
A::A() : pb(new B){}
A::~A(){delete pb;}
int& A::operator[](int n)
{ return pb->array[n];}
int main(int argc, char* argv[])
{
A a;
// uses A's subscript operator to access B's private member data
a[0] = 5;
return 0;
}
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)