无法使用访问器设置私有静态成员变量
Can't set private static member variables with accessor
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;
}
相关文章:
- C++:是否可以使用非静态成员变量模板?
- 如何在复杂继承中访问静态成员变量
- 静态成员变量不会由 gettext 转换
- 为什么我不能像这样在静态成员函数中调用静态成员变量?
- C++ lambda - 捕获静态成员变量
- 多线程处理中的静态成员变量
- 纯标头库中静态成员变量的正确设置器和 getter
- 如何从具有专用化的类模板定义静态成员变量?
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 声明和定义类静态成员变量不会导致多重声明,这是为什么?
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 类中的静态成员变量和C++中的全局变量有什么区别?
- C++ 静态成员变量 - 文件之间的访问
- 如何在运行时使用静态成员函数初始化静态成员变量
- 模板类中嵌套类的C 静态成员变量
- 如何检查静态成员变量模板?
- 重载运算符和静态成员变量的行为
- 类的静态成员变量(受保护)的作用域
- gcc 和 clang 中 constexpr 静态成员变量的链接器错误
- dll 中静态成员变量的生存期