2012-04-03 49 views
-1

我想创建一个C++类,它可以作为我的项目的持有人,所以实现了我的类成员和函数静态,但我不知道为什么编译器可以识别内部的_nTriggerMode setTriggerMode。静态成员在C++编程

这里是我的头文件:

#pragma once 
class GrabberOptions 
{ 
private: 
    static int _nTriggerMode; 
    static int _nExposureInMicroSec; 
    static double _dFramesPerSecond; 
    static int _nExsysncOn; 

public: 
    GrabberOptions(void); 
    ~GrabberOptions(void); 
    static void setTriggerMode(int triggerMode); 
    static void setExposureInMicroSec(int exposureMicroSec); 
    static void setFramePerSecond(double framePerSec); 
    static void setExsysncOn(int exsysncOn); 

    static int getTriggerMode(); 
    static int getExposureInMicroSec(); 
    static double getFramePerSecond(); 
    static int getExsysncOn(); 
}; 

这里是.ccp文件:

#include "StdAfx.h" 
#include "GrabberOptions.h" 
int GrabberOptions::_nTriggerMode; 

INT GrabberOptions :: _ nExposureInMicroSec; double GrabberOptions :: _ dFramesPerSecond; int GrabberOptions :: _ nExsysncOn; GrabberOptions :: GrabberOptions(void) { _nTriggerMode = GRABBER_CONTROLLED; _nExposureInMicroSec = 20; _dFramesPerSecond = 1000; _nExsysncOn = 1; }

GrabberOptions::~GrabberOptions(void) 
{ 
} 

空隙setTriggerMode(INT triggerMode){ _nTriggerMode = triggerMode; }

请给我一些关于如何使用静态的想法。

+0

你会得到什么错误? – Rps 2012-04-03 16:07:46

+2

-1。 “一个错误”没有描述问题。告诉你得到什么错误。 – 2012-04-03 16:12:06

+0

可能的重复[对一个静态成员有一个未定义的引用意味着什么?](http://stackoverflow.com/questions/7092765/what-does-it-mean-to-have-an-undefined-reference - 静态成员) – Flexo 2012-04-03 16:12:09

回答

4

static类成员变量必须在类定义之外定义:

// .h file 
class GrabberOptions 
{ 
private: 
    static double _dFramesPerSecond; // declaration 

// .cpp file 
double GrabberOptions::_dFramesPerSecond = 1000; // definition 
+0

hmjd,谢谢你的回复。你可以添加我怎么可以添加我的设置器,因为我正在尝试在我的.cpp文件中的代码,\t void setTriggerMode(int triggerMode){_nTriggerMode = triggerMode; }但我不知道为什么有一个红线undet the _nTriggerMode? – user261002 2012-04-03 16:31:21

+0

看起来好像函数名称不符合类的名称。改为:void GrabberOptions :: setTriggerMode(int triggerMode)'。 – hmjd 2012-04-03 16:34:33

+0

谢谢,它确实有效:D – user261002 2012-04-03 16:38:12

4

需要初始化静态类定义之外,在一个单一的翻译单元(通常是对应的实现文件):

#include "StdAfx.h" 
#include "GrabberOptions.h" 

double GrabberOptions::_dFramesPerSecond; //initializes to 0 
//double GrabberOptions::_dFramesPerSecond = 1337; //if you want a different value 

GrabberOptions::GrabberOptions(void) 
{ 
    // _nTriggerMode  = GRABBER_CONTROLLED; 
    // _nExposureInMicroSec = 20; 
     _dFramesPerSecond = 1000; 
    // _nExsysncOn   = 1; 
} 

GrabberOptions::~GrabberOptions(void) 
{ 
} 
+0

好吧,我看到,它的形式与JAVA差别很大。非常感谢。 :D – user261002 2012-04-03 16:11:44

+0

方法是一样的吗? – user261002 2012-04-03 16:12:32

+0

@ user261002不一定,方法可以在类内定义。也是恒定积分(但你的成员不是)。 – 2012-04-03 16:13:51

1

一个类的static成员变量被一个类的所有实例共享。它们偶尔有用,但这可能不是一个例子。静态成员函数只能访问静态成员变量。

注释掉的代码显示您的类设计没有每个实例的数据;一切都是静态的。这在C++中基本上不是一个好的设计。