0

我需要在运行时设置静态浮点变量的值,但我无法做到这一点。我将举例说明我的情况

文件.h

class B {
    static float variable1;
    static float variable2;
 public:
    afunction(float a, float b);
} 

文件.cpp

#include 'afile.h'
B::afunction (float a, float b) {
    float B:variable1 = a;
    float B:variable2 = b;
} 

正如您在上面的代码中看到的那样,调用了函数“afunction”,然后必须设置变量“variable1”和“variable2”。我知道'afunction'定义中的代码是错误的,但是我需要一种在运行时设置变量1和变量2的值的方法。

如果它与我的代码相关,我正在使用 Visual Studio 6.0 开发应用程序

4

2 回答 2

1

写吧:

B::afunction (float a, float b) {
    B::variable1 = a;
    B::variable2 = b;
}

那应该行得通。

于 2013-02-11T09:09:28.293 回答
1

首先,您必须先将静态变量设置为某个值,然后才能引用它。

没有int test::m_ran = 0;你会得到undefined reference to 'test::m_ran'

#include <cstdio>

class test
{
public:
    static void run() { m_ran += 1; }
    static void print() { printf("test::run has been ran %i times\n", m_ran); }

private:
    static int m_ran;

};

int test::m_ran = 0;

int main()
{
    for (int i = 0; i < 4; ++i)
    {
        test::run();
        test::print();
    }

    return 0;
}

输出:

test::run has been ran 1 times
test::run has been ran 2 times
test::run has been ran 3 times
test::run has been ran 4 times
于 2013-02-11T09:18:38.760 回答