C ++ static method with struct parameters
I have this problem ...
I have my structure:
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 compile-time error:
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
source to share
The keyword is static
overloaded in C ++ (i.e. has multiple meanings). In the code you presented:
struct MyStruct {
};
static float MyStaticFunction( MyStruct, MyStruct );
the value static
is an internal linkage (i.e. the character will not be used outside the current translation unit. If this is present in the header, then each includes a translation unit which will receive its own copy of the function. in this case the free function function is used :
MyStruct a,b;
float f = MyStaticFunction( a, b );
It seems from trying to use it 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 a specific instance. In this case, the function can be called in one of two ways, the most common being:
MyStruct a,b;
float f = MyStruct::MyStaticFunction( a, b );
although the language also allows (I would not recommend using it, it can be confusing):
float f a.MyStaticFunction(a,b);
If confusion arises because it is like calling a member function on a
rather than calling a static member function in a class.
source to share