c++ - 通过类成员函数访问静态常量变量的问题

标签 c++

我在访问类私有(private)成员变量部分中定义的静态常量变量时​​遇到问题。具体来说,下面编写的代码可以在构造函数中输出变量,但是当我尝试通过访问函数访问它时,会出现下面讨论的错误。如果有人知道原因,我将不胜感激。

#include <iostream>
using namespace std;

class TestStaticVariables
{
 // Private member variable:
 static const double static_double_variable;
public:
 // Constructor:
 TestStaticVariables()
 {
  // Initialization:
  static const double static_double_variable = 20.0;
  cout << static_double_variable;
 }
 // Member Function:
 void test();
};

void TestStaticVariables::test()
{

当取消注释下一行时,我收到以下错误消息:

行定位工具:0:“TestStaticVariables::static_double_variable”,引用自:

 //cout << static_double_variable;
}

int main(int argc, char* const argv[])
{

 TestStaticVariables test_instance;

 return 0;
}

最佳答案

尝试在类定义之外初始化变量,这是一个工作示例:

#include <iostream>

class Foo {
    static const double _bar;

public:
    Foo();

    void Bar();
};

const double Foo::_bar = 20.0;

Foo::Foo() {
    std::cout << Foo::_bar << std::endl;
}

void Foo::Bar() {
    std::cout << Foo::_bar << std::endl;
}

int main( int argc, char *argv[] ) {
    Foo f;
    f.Bar();

    return 0;
}

关于c++ - 通过类成员函数访问静态常量变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/898387/

相关文章:

c++ - 如何访问类构造函数中创建的对象

c++ - 在命名空间 foo 中声明 swap() 然后在同一命名空间下使用 swap() 而不是 foo::swap() 是否意味着 foo::swap()?

C++ 结构和构造函数

c++ - Boost的shared_array/ptr中的数据突然被删除

c++ - 为什么下面的 C++ 代码只打印第一个字符?

c++ - GDI+:绘制位图时出现未处理的异常

C++ 模板和不明确的函数调用

c++ - 将项目数据附加到菜单项

c++ - 使用 C++ 的 vs2010 中的智能感知

c++ - 如何正确删除模板函数中的代码重复