gpt4 book ai didi

c++ - 静态成员函数访问静态私有(private)变量时链接器错误

转载 作者:行者123 更新时间:2023-11-30 02:22:12 25 4
gpt4 key购买 nike

我是 C++ 的新手,正在探索类成员和函数的静态特性。

人.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();


};

}

人.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;
}
}

主要.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)静态变量时应该怎么做?

最佳答案

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

关于c++ - 静态成员函数访问静态私有(private)变量时链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47587165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com