tags:

views:

67

answers:

3

the following code compiles fine under gcc:

class vec3
{

private:

  float data[3];

public:

  vec3(float x, float y, float z)
  {
    data[0] = x;
    data[1] = y;
    data[2] = z;
  }

  void operator =(const vec3 &v)
  {
    data[0] = v.data[0];
    data[1] = v.data[1];
    data[2] = v.data[2];
  }

  friend vec3 operator *(float a, const vec3 &v)
  {
    vec3 res(v.data[0], v.data[1], v.data[2]);
    res.data[0] *= a;
    res.data[1] *= a;
    res.data[2] *= a;
    return res;
  }

};

int main(int argc, char **argv)
{
  vec3 v(1.0, 2.0, 3.0);
  vec3 u = 2*v;
  return 0;
 }

it seems tho the operator * is defined within the class it is compiled as a non-member function because it is declared as friend. is this the standard behaviour? it seems a bit of an odd way to define a non-member function, I haven't seen this way of defining non-member friends in any text-books/faqs (normally declared within the class and defined outside).

james

A: 

It is standard behavior, and I've seen it at least once in Effective C++.

Philipp
ok, I must have skimmed over that example then.
james edge
+2  A: 
Tony
yes it is very useful, I'm just moving a load of methods from outside definitions to inside... this makes the code read a lot better and saves on a load of declarations in my class :)
james edge
@james edge: Is that sarcasm?
Martin York
+1  A: 

Yes..

According to the standard docs, 11.4 Friends - 6

A function can be defined in a friend declaration of a class if and only if the class is a non-local class (9.8), the function name is unqualified, and the function has namespace scope.

Example:

class M {
friend void f() { } // definition of global f, a friend of M,
// not the definition of a member function
};

Note that the function name is unqualified and it is a global function which has the scope of the associated namespace in where it is defined..

liaK