首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用访问器设置私有静态成员变量

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

Stack Overflow用户
提问于 2014-03-05 03:06:52
回答 3查看 1.1K关注 0票数 0

H有一些静态成员变量。Read.cpp包括Zombie.h,它知道需要进入这些变量中的值。我希望read.cpp用以下方式设置这些变量

代码语言:javascript
复制
int Zombie::myStaticInt = 4;

代码语言:javascript
复制
Zombie::setStaticVar(4);

我已经尝试了我所能想到的一切,包括使用公共静态访问器函数,甚至将静态变量本身公开,但是我得到了很多“未定义的引用”或“无效使用限定名”错误。通过查看这些内容,我了解了如何从Zombie.cpp设置Zombie.h的私有静态成员变量,但我没有Zombie.cpp文件,只有read.cpp。我可以从Read.cpp中设置它们吗?如果可以,如何设置?

代码语言:javascript
复制
// 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 ()以解决这个问题)

代码语言:javascript
复制
invalid use of qualified-name 'Zombie::a'
invalid use of qualified-name 'Zombie::b'
invalid use of qualified-name 'Zombie::c'
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-05 03:35:26

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

代码语言:javascript
复制
int Zombie::a;
int Zombie::b;
int Zombie::c;

编辑是您的编辑,您不能将它们放在方法中。您必须将它放在.cpp文件的最外层。

票数 2
EN

Stack Overflow用户

发布于 2014-03-05 03:38:52

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

代码语言:javascript
复制
int Zombie::a;
int Zombie::b;
int Zombie::c;

您所得到的链接器错误是告诉您,这些行丢失了。

票数 1
EN

Stack Overflow用户

发布于 2014-03-05 03:17:45

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

zombie.h

代码语言:javascript
复制
#ifndef ZBE_H
#define ZBE_H

class Zombie
{
public:
    static int myStaticInt;

    Zombie();
};
#endif

read.cpp

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22187682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档