Ste*_*ham 11 c++ pointers class function vector
好吧,我的主要是:
void somefunction();
int main()
{
//bla bla bla
SomeClass myclass = SomeClass();
void(*pointerfunc)() = somefunction;
myclass.addThingy(pointerfunc);
//then later i do
myclass.actionWithDiffrentOutcomes();
}
void somefunction()
{
//some code
}
Run Code Online (Sandbox Code Playgroud)
在课堂上:
class SomeClass()
{
public:
void addThingy(void (*function)());
void actionWithDiffrentOutcomes();
private:
std::vector<void (**)()> vectoroffunctions;
}
SomeClass::addThingy(void (*function)())
{
vectoroffunctions.push_back(&function);
}
SomeClass::actionWithDiffrentOutcomes()
{
(*vectoroffunctions[0])();;
}
Run Code Online (Sandbox Code Playgroud)
我对指针有点新意,但我阅读了我的c ++书籍,谷歌搜索,分机.这似乎是正确的,编译,运行,但当我调用"actionWithDiffrentOutcomes()"时,我得到访问冲突.我不知道该怎么做.这似乎是正确的,但事情显然是错误的.那么当定义在另一个类中时,如何从类中调用函数呢?
我这样做是因为我无法将每个选项硬编码到switch语句中.
Man*_*rse 14
你的代码几乎是正确的.你的向量错误地指向指向函数的指针,而不是简单地指向函数.addThingy将function指针的地址添加到vector,但该指针超出了下一行的范围.
更改您的代码如下:
//Store pointers to functions, rather than
//pointers to pointers to functions
std::vector<void (*)()> vectoroffunctions;
SomeClass::addThingy(void (*function)())
{
//Don't take the address of the address:
vectoroffunctions.push_back(function);
}
Run Code Online (Sandbox Code Playgroud)
此外,您在其余代码中有很多语法错误,这些错误应该阻止代码编译.
问题出在这里:
vectoroffunctions.push_back(&function);
Run Code Online (Sandbox Code Playgroud)
您正在添加局部变量的地址.从函数返回后,局部变量将被销毁.向量存储的地址指向被破坏的对象,这就是运行时出现"访问冲突"错误的原因.
要解决此问题,请执行此操作:
首先改变这个
std::vector<void (**)()> vectoroffunctions;
Run Code Online (Sandbox Code Playgroud)
对此:
std::vector<void (*)()> _functions; //vector of function-pointer-type
//I changed the name also!
Run Code Online (Sandbox Code Playgroud)
这实际上与:
std::vector<void()> _functions; //vector of function-type
Run Code Online (Sandbox Code Playgroud)
现在这样做:
_functions.push_back(function); //add copy!
Run Code Online (Sandbox Code Playgroud)
为了使其更灵活,您可以使用模板以及std::function:
class A
{
public:
template<typename Function>
void add(Function && fn)
{
_functions.push_back(std::forward<Function>(fn));
}
void invoke_all()
{
for(auto && fn : _functions)
fn();
}
private:
std::vector<std::function<void()>> _functions;
};
Run Code Online (Sandbox Code Playgroud)
现在您可以使用它来存储函数和函子:
void myfunction() { std::cout << "myfunction" << std::endl ; }
struct myfunctor
{
void operator()() { std::cout << "myfunctor" << std::endl ; }
};
A a;
a.add(myfunction); //add function
a.add(myfunctor()); //add functor!
a.invoke_all();
Run Code Online (Sandbox Code Playgroud)
输出(在线演示):
myfunction
myfunctor
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
33110 次 |
| 最近记录: |