无法使用访问器设置私有静态成员变量



Zombie.h有一些静态成员变量。Read.cpp,包括Zombie.h,知道需要进入这些变量的值。我想阅读.cpp用类似

int Zombie::myStaticInt = 4;

Zombie::setStaticVar(4);

我已经尝试了我能想到的一切,包括使用公共静态访问器函数,甚至将静态变量本身设为公开,但我收到了很多"未定义的引用"或"无效使用限定名称"错误。通过研究这些,我发现了如何从Zombie.cpp设置Zombie.h的私有静态成员变量,但我没有Zombie.cpp文件,只是读取.cpp。我可以改为从读取.cpp设置它们吗?如果是,如何设置?

// In Zombie.h
class Zombie {
public:
    static void setMax(int a_in, int b_in, int c_in) {
        a = a_in;
        b = b_in;
        c = c_in;
    }
private:
    static int a, b, c;
}
// In read.cpp
#include "Zombie.h"
...
main() {
    int Zombie::a; // SOLUTION: Put this outside the scope of main and other functions
    int Zombie::b; // SOLUTION: Put this outside the scope of main and other functions
    int Zombie::c; // SOLUTION: Put this outside the scope of main and other functions
    int first = rand() * 10 // Just an example
    int second = rand() * 10 // Just an example
    int third = rand() * 10 // Just an example
    Zombie::setMax(first, second, third);
    return 0;
}

这产生(更新)(将main的前三行移到main()之外来解决这个问题)

invalid use of qualified-name 'Zombie::a'
invalid use of qualified-name 'Zombie::b'
invalid use of qualified-name 'Zombie::c'
你必须在

某处定义a,b,c。到目前为止,您只宣布它们存在。在某些.cpp文件中,在外部范围内,您需要添加:

int Zombie::a;
int Zombie::b;
int Zombie::c;
编辑

重新编辑,你不能把它们放在方法中。您必须将其放在.cpp文件的最外层范围。

与在每个

对象中分配存储的非静态变量不同,静态变量必须在类之外进行存储。为此,您可以为 .cpp 文件中的变量创建定义。它们进入哪个文件并不重要,尽管为了方便起见,它们应该使用类的代码。

int Zombie::a;
int Zombie::b;
int Zombie::c;

您收到的链接器错误告诉您缺少这些行。

你的问题是你还没有实现僵尸类。您的代码在这里:

僵尸

#ifndef ZBE_H
#define ZBE_H
class Zombie
{
public:
    static int myStaticInt;
    Zombie();
};
#endif

阅读.cpp

#include <stdio.h>
#include <iostream>
#include "zombie.h"
int Zombie::myStaticInt = 1;
Zombie::Zombie()
{
}
int main()
{ 
    cout << "OOOK: " << Zombie::myStaticInt << endl;
    Zombie::myStaticInt = 100;
    cout << "OOOK: " << Zombie::myStaticInt << endl;
    return 0;
}

最新更新