【问题标题】:How and where to define class variable when using header files in C++在 C++ 中使用头文件时如何以及在何处定义类变量
【发布时间】:2013-06-24 22:16:33
【问题描述】:
/*
 * CDummy.h
 */
#ifndef CDUMMY_H_
#define CDUMMY_H_

class CDummy {

public:
    CDummy();
    virtual ~CDummy();
};

#endif /* CDUMMY_H_ */

我读到不应在头文件中声明类变量。这对吗? 所以我在下面的cpp文件中声明:

/*
 * CDummy.cpp
*/

#include "CDummy.h"

static int counter = 0; //so here is my static counter. is this now private or public? how can i make it public, i cannot introduce a public block here.

CDummy::CDummy() {
  counter++;

}

CDummy::~CDummy() {
    counter--;
}

使用此代码我无法从我的主程序访问类变量....

谢谢

【问题讨论】:

    标签: c++ header class-variables


    【解决方案1】:

    静态整数计数器 = 0; //所以这是我的静态计数器。这现在是私人的还是公共的?怎样才能公开,这里不能介绍公开区块。

    从代码中我看到counter 只是一个全局静态变量,因为它没有在您的CDummy 中的任何地方声明

    静态变量应该是公共的,这样你就可以在类声明之外初始化它们。要公开,您的代码应如下所示:

    class CDummy {
    public:
       static int count;
       CDummy();
       virtual ~CDummy();
    };
    // inside CDummy.cpp
    int CDummy::count = 0;
    

    Here你可以阅读更多关于如何在类声明中使用静态变量。

    【讨论】:

      【解决方案2】:

      一个“类变量”需要属于一个类。所以它必须在类定义中声明。如果类定义在头文件中,那么类变量声明也必须在头文件中。

      类变量的定义应该放在一个实现文件中,通常是定义类成员的那个文件。这是一个简化的示例:

      Foo.h

      struct Foo
      {
        void foo() const;
        static int FOO;   // declaration
      };
      

      Foo.cpp

      void Foo::foo() {}
      int Foo::FOO = 42; // definition
      

      你有什么:

      static int counter = 0;
      

      是一个静态变量,不是任何类的静态成员。只是非成员静态变量,对CDummy.cpp的编译单元是静态的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 1970-01-01
        • 2013-08-19
        • 1970-01-01
        • 2020-10-27
        相关资源
        最近更新 更多