Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

function in a struct

Status
Not open for further replies.

sedawk

Programmer
Feb 5, 2002
247
US
Hi,

What is wrong with this?

Code:
#include <stdio.h>

struct X {  // or class X { public:
        static int f();
};

int f(void) {
        static int x = 0;
        x++;
        return x;
}

int main(void) {
        X X1;
        int j;
        for (j = 0; j < 5; j++) {
                printf("value of f(x) is: %d\n", X1::f()); // or X1.f()
        }

        return 0;
}

It can't find X1, "error: `X1' is not a class or namespace". Why?
 
I missed the function definition. It should be:

Code:
int X::f(void) {
        static int x = 0;
        x++;
        return x;
}

And call it by X1.f().
 
In C++ there's not much wrong with it.
In C, it's completely invalid since C isn't an object oriented language.
 
Yes, this is intended to be a C++. I don't think I can declare a function in struct in C.
 
Did you mean [tt]X::f()[/tt] instead of [tt]X1::f()[/tt]?

(Also, this is the C forum, so you can see why one might have assumed you were asking about C ;-) )
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top