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
Yes..
According to the standard docs,
11.4 Friends - 6A 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:
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..