2015-12-30 79 views
1
#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; 
    } 

我有2个与Visual Studio连接错误:C++类和朋友的Visual Studio链接错误

Error 1 error LNK2019: unresolved external symbol "void __cdecl f(class A &)" ([email protected]@[email protected]@@Z) referenced in function _main

Error 2 error LNK2001: unresolved external symbol "private: static int A::x" ([email protected]@@0HA)

请帮忙解决这些错误

+0

有一个在VS”编辑器中自动缩进功能,请使用它!它使代码更具可读性。也就是说,提取最小的例子,你是不是需要更大。 –

回答

1

静态成员变量只存在一次,并在类的对象之间共享。因为静态成员变量不是单个对象的一部分,你必须明确地定义静态成员。通常情况下,明确地定义被放置在类的源文件(CPP)在:

头文件:

class A 
{ 
    static int x; 
}; 

源文件:

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

对于第一错误:

您声明friend void f(A &a);,表明f是需要访问A的成员非成员函数。

但是,你仍然定义f的类里面,使它成为一个成员函数。要解决这个连接错误,你应该在功能f移到类之外。