静态成员函数
1)使用类的静态成员函数来访问类的私有静态数据成员,不可以调用类的非静态成员。因为静态成员函数不含this指针。
2)静态成员函数的声明除了在类体中的函数声明前加上关键字static, 以及不能声明为const 或volatile之外,与非静态成员函数相同。出现在类体外的函数定义不能指定关键字static。
3)静态成员函数的地址可用普通函数指针储存,而普通成员函数地址需要用 类成员函数指针来储存。
1 2 3 4 5 6 |
class base{ static int func1(); int func2(); }; int (*pf1)()=&base::func1;//普通的函数指针 int (base::*pf2)()=&base::func2;//成员函数指针 |
4)静态成员是可以独立访问的,也就是说,无须创建任何对象实例就可以访问。 非常有用!!!
1 2 3 |
CString cs(m_rawInfo.FilePath); std::string path((LPCTSTR)cs); TmdsStream result = TmdsStream(DmaCapture::Open(path));//调用方式 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
//类内定义 class CLASS_DECLSPEC DmaCapture : public Serializable{ private: int _size; //the size in words int _apparentSize; //The size of the capture that actually contains good data int* _captureData; //The number of bytes included in the DmaCapture - should be a multiple of the size of (int) DmaCapture(int bytes); DmaCapture(int bytes, int apparentSize); public: static DmaCapture Open(std::string filePath); }; DmaCapture::DmaCapture(int bytes){ if((bytes % sizeof(int)) != 0) throw std::runtime_error("Bytes needs to be a multiple of sizeof(int)"); _size = bytes / sizeof(int); _captureData = new int[bytes / sizeof(int)];//开辟一块内存空间 _apparentSize = _size; } //类体外的函数定义 DmaCapture DmaCapture::Open(std::string filePath){ FILE* pFile = nullptr; // get the file stream fopen_s( &pFile, filePath.c_str(), "rb" ); // set the file pointer to end of file fseek( pFile, 0, SEEK_END ); // get the file size int Size = ftell( pFile ); //字节数目 DmaCapture cap(Size); //返回一个DmaCapture对象 rewind(pFile); fread(cap._captureData, sizeof(int), cap.Size(), pFile);//读入内容到内存块中 /*int DmaCapture::Size(){ return this->_apparentSize; */ ::fclose(pFile); return cap; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
将capture对象右值引用给TmdsStream的实例对象 TmdsStream::TmdsStream(DmaCapture&& capture) : _capture(std::move(capture)) {} //调用move函数进行右值引用 /* // TEMPLATE FUNCTION move template<class _Ty> inline typename tr1::_Remove_reference<_Ty>::_Type&& move(_Ty&& _Arg) { // forward _Arg as movable return ((typename tr1::_Remove_reference<_Ty>::_Type&&)_Arg); }*/ //将capture对象的内存块清空 DmaCapture::DmaCapture(DmaCapture&& other) :_size(other._size),_captureData(other._captureData), _apparentSize(other._apparentSize){ other._captureData = nullptr; } //析购Dmacapture对象,删除空指针 DmaCapture::~DmaCapture(){ delete[] this->_captureData; } |