静态函数在C ++中调用非静态函数 [英] Static function call non static function in C++

查看:122
本文介绍了静态函数在C ++中调用非静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的课程:

I have a class like::

Class Test
{
  public:
  void Check(){//dosomething};
  static void call(){//I want to call check()};
};

因为call()是静态成员,所以它不能调用非静态函数,所以我认为在call()中使用Check()是创建Test指针,然后指向Check(),但是我认为这不好,是否有更好的方法来做到这一点?我可以重写静态函数中的所有内容,因此不需要再次调用Check(),但是我想要的是重用Check()中的代码并避免重复的代码.

Because call() is a static member, so it can't call non-static functions, so I think to use Check() in call() is to create Test pointer and then point to Check(), but I think it is not good, is there a better way to do this? I can rewrite all of things in the static function, so I don't need to call Check() again, but what I want is to reuse the code in Check() and avoid repeated code.

推荐答案

由于需要一个实例,因此您必须创建一个实例,使用静态实例,或者将其粘贴到 call():

Since you need an instance, you either have to create one, use a static instance, or pas it to call():

Class Test
{
  private:
  static Test instance;

  public:
  void Check(){//dosomething};
  // use one of the following:
  static void call(Test& t){ t.check(); };
  static void call(){ Test t; t.check(); };
  static void call(){ instance.check(); };
};

这篇关于静态函数在C ++中调用非静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆