1
votes
 #include <iostream>

    using namespace std;

    class A
    { 
        static int x; 
        int y; 

     private: 
        friend void f(A &a); 

     public: 
     A() 
     { 
          x=y=5; 
     } 

     A(int xx,int yy) 
     { 
        x=xx; 
        y=yy; 
     } 

     //static void getVals(int &xx, int &yy); 
     void getVals(int *xx, int *yy) 
     { 
        *xx=x; 
        *yy=y; 
     } 

     void f(A &a) 
     { 
        int x,y; 
        a.getVals(&x,&y); 
        cout << a.x << "; " <<a.y << endl; 
      } 
    }; 

    int main() 
    { 
        A a1; 
        A a2(3,8); 

        f(a1); 
        f(a2); 

        return 0;
    } 

I got 2 link errors with visual studio:

Error 1 error LNK2019: unresolved external symbol "void __cdecl f(class A &)" (?f@@YAXAAVA@@@Z) referenced in function _main

Error 2 error LNK2001: unresolved external symbol "private: static int A::x" (?x@A@@0HA)

please help to resolve these errors

3
There is an autoindent function in VS' editor, please use it! It makes code more readable. That said, extract a minimal example, yours is much bigger than necessary.Ulrich Eckhardt

3 Answers

1
votes

Static member variables exists once and are shared between the objects of the class. Because static member variables are not part of the individual objects, you must explicitly define the static member. Usually the explicitly definition is placed in the source file (cpp) of the class:

header file:

class A
{ 
  static int x;
};

source file:

int A::x = 0; // <- explicitly definition and initialization
0
votes

You need to add int A::x; after the class declaration. You can see this link : http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

0
votes

For the first error:

You declare friend void f(A &a);, indicating that f is a non-member function that needs access to A's members.

However, you still define f inside the class, making it a member function. To resolve this linker error, you should move the function f to outside the class.