저는 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
개인 정적 변수로 사용할 때 어떻게해야합니까?
'private'로 변경하지 않고 단지'Person Person :: idcount;'로 정의하고,'Person.cpp'에서 더 잘 정의하십시오. – songyuanyao
오류를 표시하지는 않았지만이 답변의 맨 아래에 설명되어 있습니다. https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external -symbol-error-and-how-do-i-fix/12574407 # 12574407 – chris
예 person.cpp에 추가 - 오류를 해결하지만 그 뒤에있는 이론은 무엇인지 궁금해합니다. 그래서 모든 정적 int, private 또는 public은 클래스 정의에서 선언되어야합니까? – hariudkmr