正确使用静态类成员

时间:2011-04-08 17:46:00

标签: c++ static linker

拥有静态类成员的正确方法是什么?

我正在尝试创建一个度量类,以便我可以在所有文件中包含“metrics.h”,并使用它中的某些变量(静态变量)来跟踪多个单独编译的库中的时序信息。

其中一个库对于所有其他库都是通用的,所以当我使用metrics.h编译它时,它编译得很好,但是当我尝试编译其中一个使用common的附加库时,我得到了“多重定义”错误,以及一些未定义的引用。

这个常见的指标类应该是什么样的?我不想要实例化它来使用变量,我只想使用像

这样的东西

Metrics :: startTime = ....

和Metrics :: calcTime = ....

在公共库中,或者是链接到公共

的其中一个库

5 个答案:

答案 0 :(得分:2)

最好将它们全部打包成一个静态struct成员,而不是定义一些静态成员。

比直接实例化和访问此静态成员更好的是将其隐藏在getter函数中。

class metrics {
    ...
    struct measurements { // struct may be private; you can still access
        double startTime; // the members of the result of the getter fn.
        double calcTime;
        ...
    };

public:
    static measurements &getMeasurements() {
        static measurements instance;
        return instance;
    }
};

使用此功能,您无需向.cpp文件添加任何内容。 measurements对象instance是在第一次调用getMeasurements时创建的,并且为所有后续调用返回相同的对象。

答案 1 :(得分:1)

在头文件中:

class Metrics {
  public:
  static int startTime ;
  } ;

中只有一个 cpp文件:

int Metrics::startTime ;

答案 2 :(得分:1)

// metrics.hpp
class metrics {
static int i; // declaration
};

// metrics.cpp
int metrics::i(0); // definition
除此之外,它是构造函数的正确实现

答案 3 :(得分:1)

您不应该以这样的方式组合库,即相同的代码最终会多次链接到程序中。在一个库中隔离您的度量标准类,以及应该打包的任何其他类(请参阅Robert Martin发布的六个打包原则以获得指导)。将其他依赖它的类放在其他库中(或者如果这些包装原则显示它们属于一个,则将它们全部放在一个库中)。链接程序时,链接所需的所有库,包括依赖于metrics类的库和包含度量类的(一)库。

答案 4 :(得分:0)

<强> Metrics.h

#ifndef _METRICS_H
#define _METRICS_H

class Metrics {
    ...
    public:
        Metrics();
        //declare the static variables in the header for the class
        static int startTime;
        static int calcTime;
}

#endif

<强> Metrics.cpp

#include "Metrics.h"

Metrics::Metrics(){
    ...
}

//define and initialize the variables in the implementation of the class
int Metrics::startTime = 15;
int Metrics::calcTime = 20;

<强>的main.cpp

#include "Metrics.h"

int main(){
    //use the static variables elsewhere
    int a = Metrics::startTime;
}