问题描述
大家好
我必须通过使用指针函数来面对类中的问题.
例如
头文件
testPtr.h
Hi All
I have to face problem in classes by using pointers function.
for example
header file
testPtr.h
class testPtr
{
float *add(float *a,int n)
};
主要是该类的使用
in main the use of this class
//testing.cpp
// object of class
testPtr testPtrObject();
void main
{
testPtrObject.add(a,n);
}
float testPtr::*add(float a int n)
{
----------
-------
}
我只在有指针的情况下才可以面对问题
否则,如果我在头文件中使用简单的函数,然后通过在主类中创建该类的对象来调用这些函数,那么我可以轻松地访问该函数,并通过创建该类的对象来使用它们,只要我需要它
请指导我在使用指针函数
i ve to face the problem only in case of pointer
other wise if i use simple functions in header file and then call these function by creating the objects of that class in main class i can easily access that functions and use them any whaere i neede by creating the object of that class
kindly guide me what to do in case of pointer function
推荐答案
typedef float* (testPtr::*MemFuncPtr) (float *a, int n);
MemFuncPtr p = &testPtr::add;
// calling sequence:
(testPtrObject.*p) (&a, n);
如您所见,语法很尴尬,是C ++的弱点之一.
与其将函数的指针和对象的指针分开处理,不如将它们捆绑在一起成为一个对象.这就是通常所说的委托.
您可以在CodeProject上找到很多有关委托的好文章,例如:
成员函数指针和最快的C ++代理
希望您能走上正轨.
As you see, the syntax is awkward and one of the weaker points of C++.
Instead of handling the pointer to function and the object pointer separately, why not bundle them together into a single object. That''s what is generally called a delegate.
You find a lot of good articles here on CodeProject about delegates, for example this one:
Member Function Pointers and the Fastest Possible C++ Delegates
Hope that gets you on track.
class testPtr
{
public:
float *add(float *a,int n);
};
实现应如下所示:
The implementation should look like this:
float* testPtr::add(float* a int n)
{
//----------
//-------
}
然后可以这样使用:
It can then be used like this:
int main()
{
testPtr testPtrObject;
float b = 1.0;
float* a =&b;
int n = 2;
float* c = testPtrObject.add(a,n);
testPtr* testPtrObjectPtr = new testPtr();
float* c = testPtrObjectPtr->add(a,n);
delete testPtrObjectPtr;
}
这篇关于在VC ++类中使用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!