我可以在运行时初始化静态浮点变量吗?

时间:2013-02-11 09:04:06

标签: c++ visual-studio mfc

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

afile.h

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

afile.cpp

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

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

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

2 个答案:

答案 0 :(得分:1)

只需写下:

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

这应该有效。

答案 1 :(得分:0)

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

如果没有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