簡體   English   中英

靜態成員函數訪問靜態私有變量時鏈接器錯誤

[英]Linker error when static member function access static private variable

我是c ++的新手,並且在類成員和函數上探索靜態特性。

person.h

#include <iostream>

using namespace std;

namespace school 
{

class Person 
{

    public:
        static const int MAX=99;

    private:    
        static int idcount;

    public:
        static void setID(int id) { idcount = id;}
        static int getID() { return idcount;}

    private:
        string name;    

    public:
        Person();
        Person(const Person &other);
        ~Person();  


};

}

Person.cpp

#include "person.h"

namespace school 
{

    //Constructor
    Person::Person()
    {
        this->name = "";
        cout << "object created" << endl;
    }

    //Copy Constructor
    Person::Person(const Person &other)
    {
        this->name = other.name;
    }

    //Destructor
    Person::~Person()
    {
        cout << "Destructor Called" << endl;
    }
}

main.cpp中

#include "person.h"

int main()
{


    cout << school::Person::MAX << endl;
    school::Person::setID(5);
    cout << school::Person::getID() << endl;

    return 0;
}

我編譯上面的代碼時收到以下鏈接器錯誤。 但是當我將idcount更改為public並將其聲明為main(int Person :: idcount;)時,我沒有任何問題。

D:\Hari\Project\CPP_Practise\build>mingw32-make
[ 50%] Built target person
Scanning dependencies of target app
[ 75%] Building CXX object CMakeFiles/app.dir/chapter2/classes2.cpp.obj
[100%] Linking CXX executable app.exe
CMakeFiles\app.dir/objects.a(classes2.cpp.obj): In function 
`ZN6school6Person5se
tIDEi':
D:/Hari/Project/CPP_Practise/chapter2/person.h:21: undefined reference to 
`schoo
l::Person::idcount'
CMakeFiles\app.dir/objects.a(classes2.cpp.obj): In function 
`ZN6school6Person5ge
tIDEv':
D:/Hari/Project/CPP_Practise/chapter2/person.h:22: undefined reference to 
`schoo
l::Person::idcount'
collect2.exe: error: ld returned 1 exit status
CMakeFiles\app.dir\build.make:97: recipe for target 'app.exe' failed
mingw32-make[2]: *** [app.exe] Error 1
CMakeFiles\Makefile2:103: recipe for target 'CMakeFiles/app.dir/all' 
failed
mingw32-make[1]: *** [CMakeFiles/app.dir/all] Error 2
Makefile:82: recipe for target 'all' failed
mingw32-make: *** [all] Error 2

當我將它用作私有靜態變量時,我該怎么辦?

1.Static變量意味着它為該類創建的所有對象都是通用的。 2.在頭文件中寫入的任何內容都充當藍圖,即它不為其分配內存。 因此,所有靜態變量都在cpp實現文件中定義。 編譯器為cpp文件中定義的內存分配內存。

Person :: i仍然需要定義(在類體外):int Person :: i;

只有那些未在體內分配值的靜力學才需要在外部定義。 並且只有非易失性常數積分才能具有這樣的體內分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM