H有一些静态成员变量。Read.cpp包括Zombie.h,它知道需要进入这些变量中的值。我希望read.cpp用以下方式设置这些变量
int Zombie::myStaticInt = 4;或
Zombie::setStaticVar(4);我已经尝试了我所能想到的一切,包括使用公共静态访问器函数,甚至将静态变量本身公开,但是我得到了很多“未定义的引用”或“无效使用限定名”错误。通过查看这些内容,我了解了如何从Zombie.cpp设置Zombie.h的私有静态成员变量,但我没有Zombie.cpp文件,只有read.cpp。我可以从Read.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'发布于 2014-03-05 03:35:26
您必须在某个地方定义a,b,c。到目前为止,你只宣布它们存在。在某些.cpp文件中,在外部范围内,您需要添加:
int Zombie::a;
int Zombie::b;
int Zombie::c;编辑是您的编辑,您不能将它们放在方法中。您必须将它放在.cpp文件的最外层。
发布于 2014-03-05 03:38:52
与在每个对象中分配存储空间的非静态变量不同,静态变量必须将其存储在类之外。为此,您可以为.cpp文件中的变量创建定义。它们进入哪个文件并不重要,尽管为了方便起见,它们应该与类的代码一起使用。
int Zombie::a;
int Zombie::b;
int Zombie::c;您所得到的链接器错误是告诉您,这些行丢失了。
发布于 2014-03-05 03:17:45
你的问题是你还没有实现僵尸类。你的代码在这里:
zombie.h
#ifndef ZBE_H
#define ZBE_H
class Zombie
{
public:
static int myStaticInt;
Zombie();
};
#endifread.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;
}https://stackoverflow.com/questions/22187682
复制相似问题