静态成员函数访问静态私有变量时链接器错误

时间:2017-12-01 05:27:21

标签: c++ class static

我是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

当我将它用作私有静态变量时,我该怎么办?

2 个答案:

答案 0 :(得分:2)

1.静态变量意味着为该类创建的所有对象都是通用的。 2.在头文件中写入的任何内容都充当蓝图,即它不为其分配内存。因此,所有静态变量都在cpp实现文件中定义。编译器为cpp文件中定义的内存分配内存。

答案 1 :(得分:0)

Person :: i仍然需要定义(在类体外):     int Person :: i;

只有那些未在身体内部分配值的静力学才需要在外部定义。只有非易失性常数积分可以进行这样的体内分配。