2015-12-30 85 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移到類之外。