3

i have this problem...

i have a my struct:

typedef struct Mystruct{
  float a;
  float b;
}

and a static method:

float static MyStaticMethod(MyStruct a, MyStruct b);

when i call this method:

Mystruct s;
s.a = 1;
s.b = 2;

Mystruct t;
t.a = 1;
t.b = 2;

MyClass.MyStaticMethod(s,t);

i have this error at compile time:

Error   51  error C2228: left of '.MyStaticMethod' must have class/struct/union

Error   50  error C2275: 'MyClass' : illegal use of this type as an expression
Safari
  • 11,437
  • 24
  • 91
  • 191
  • 1
    The use of `typedef` in the definition of `Mystruct` is useless. I would recommend that you remove it, but if you really need the *small* difference that it makes in C++, you need to provide a name for the typedef `typedef struct MyStruct {..} MyStruct;`. Again, I would just drop it. More [here](http://stackoverflow.com/a/1675446/36565), note that even if the main focus is C, the answer also deals with C++ – David Rodríguez - dribeas Apr 04 '12 at 11:53

3 Answers3

9

You need to call it using a scope resolution operator:

MyClass::MyStaticMethod(s,t);
       ^^
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

apart from using "MyClass::MyStaticMethod(s,t);", you could also call the static method on an instance:

MyClass instance;
instance.MyStaticMethod(s,t);

and it should read:

typedef struct {
  float a;
  float b;
} Mystruct;

(the new typename comes last)

umläute
  • 28,885
  • 9
  • 68
  • 122
1

The keyword static is overloaded in the C++ language (i.e. it has multiple meanings). In the code that you presented:

struct MyStruct {
};
static float MyStaticFunction( MyStruct, MyStruct );

the meaning of static is internal linkage (i.e. the symbol will not be usable outside of the current translation unit. If this is present in a header, then each including translation unit will get it's own copy of the function. In this case, usage is that of a free function:

MyStruct a,b;
float f = MyStaticFunction( a, b );

It seems from the attempt to use it that what you meant was using static in this alternate scenario:

struct MyStruct {
   static float MyStaticFunction( MyStruct, MyStruct );
};

where it has a different meaning: the member belongs to the class, not to a particular instance. In this case, the function can be called in one of two ways, the most common one is:

MyStruct a,b;
float f = MyStruct::MyStaticFunction( a, b );

even though the language also allows (I would not recommend using it, it might be confusing):

float f a.MyStaticFunction(a,b);

Where the confusion arises because it looks like calling a member function on a, rather than calling a static member function on the class.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489