如何在C++中调用函数内部的函数?
问题:通过C++函数,我需要运行线程函数,该函数又调用另一个Singleton C++函数。这个被调用的函数会调用C函数(它运行一个无限循环来改变每10毫秒的嵌入式系统状态)。如何在C++中调用函数内部的函数?
问题:如何在C++中调用函数内的函数?我是否需要分配实例来调用第二个函数?
请参考示例代码并给出您的想法是否正确或错误。
我有一个单独的类说辛格尔顿
class Singleton
{
private : // constructors and values
public :
void runThread();
Singleton getInstance();
bool ChangeStatus(int a);
};
void Singleton:: runThread()
{
changeStatus(7); // is this is right way to call function inside function
}
bool Singleton:: changeStatus(int a);
{
// This calls C function which changes the status of embedded system
}
void main()
{
// create instance of singleton class
Singleton *instance1 = Singleton::getInstance();
instance1.runThread();
/* will this call the function changeStatus and will this
changeStatus function will change status of embedded system
assuming the c function to change status is working fine.
*/
}
请无视基本的语法错误。
当我打电话从主要的runThread
功能将它成功地调用changeStatus功能还是需要指定一个多实例内runThread调用changeStatus像辛格尔顿 instance2 = Singleton::getInstance(); instance2->changeStatus
写入的函数调用是正确的。当你在一个不是静态的成员函数中,并且你调用另一个成员函数时,它会在同一个实例上调用它。如果您需要访问指向调用函数的实例的指针,则还可以使用关键字this
。
所以你也可以写this->changeStatus(7);
它也可以正常工作。
这就是说,我应该从阅读你的代码中警告你,现在写的不是创建一个新的线程,而是在主线程中运行该函数。如果你想产生一个额外的线程,你需要代码来具体做到这一点。它也不会重复检查任何内容,但这些可能是您为了简化问题而省略的细节。
嗨基思,感谢您的答复。那么我对使用这个指针有点困惑,但你已经清除了我的疑惑。感谢那。也是,我已经写了很多细节来简化事情。 – samantha 2012-03-07 17:44:56
在代码编写(修正后所有明显的错误)Singleton::runThread()
,当在instance1
上调用时,确实会在相同的instance1
上调用Singleton::changeStatus(int)
。
谢谢celtschk。 – samantha 2012-03-06 23:29:25
您有问题要问?如果是这样,那是什么? – 2012-03-06 22:30:59
对不起基思,我不是很清楚。我更新了我的问题。请参考它,并分享您的想法 – samantha 2012-03-06 22:36:45
** void ** getInstance(); ? instance1 **。** runThread(); ? – 2012-03-06 22:37:47