2013-02-11 50 views
0

我需要在运行时设置静态浮点变量的值,但我无法做到这一点。 我会提供示例来阐述我的情况我可以在运行时初始化静态浮点变量吗?

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; 
} 

当您在功能“机能缺失”上面的代码中看到被称为然后必须设置变量'variable1'和'variable2'。我知道'afunction'定义中的代码是错误的,但是我需要一种方法来设置运行时变量1和变量2的值。

如果这是有关我的代码,我使用的Visual Studio 6.0开发应用程序

+0

你试过了吗?它有用吗? – 2013-02-11 09:05:55

+0

是的,我尝试了我在示例中显示的方式,它不起作用。在当前范围内给出错误'定义或重新声明非法' – user2060711 2013-02-11 09:06:51

+1

** 1 **您选择的C++教科书告诉您如何将值赋给变量? ** 2 **为什么使用已经过期至少10年的编译器? – 2013-02-11 09:09:57

回答

1

只要写:

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

这应该工作。

+0

它应该工作,如果你只是添加几个冒号(':')。 – 2013-02-11 09:13:09

+0

@JoachimPileborg THX的说明,我只是复制代码,并没有发现, – 2013-02-11 09:14:34

+0

@ user2060711:这是伟大的,你给了我们的错误代码,但消息也会帮助太... – 2013-02-11 09:16:01

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