【问题标题】:C++ error C2352: 'CSchedulerDlg::Select' : illegal call of non-static member functionC++ 错误 C2352:'CSchedulerDlg::Select':非法调用非静态成员函数
【发布时间】:2016-01-12 18:57:25
【问题描述】:

我正在尝试修改和改进 C++ 中的作业调度程序应用程序

许多成员函数被声明为static,因此不能作用于非静态成员变量。

在尝试向类添加附加功能时会出现问题。特别是,我想知道是否可以在静态成员函数的定义中调用非静态成员函数。

也就是说,假设我们有成员函数声明:

static void email(CString message);
CRecordset * Select(CString SQL, CDatabase* dataBase);

我想从email 函数的实现中调用Select 函数。但我得到一个错误:

error C2352: 'CSchedulerDlg::Select' : illegal call of non-static member function

这个错误是有道理的,因为静态成员函数不能作用于当前对象,但我仍然需要在 email 函数中执行 Select 函数。是否存在解决方法?

导致错误的相关代码是:

void CSchedulerDlg::email(CString message)
{
    CRecordset * emails = Select("some SQL query", db);
}

其中static CDatabase* db是类中的私有成员变量。

【问题讨论】:

  • 您实际上并没有显示产生错误的代码行(以及附近的相关行)。包括导致错误的代码。
  • @abelenky 我添加了这个
  • 那里可能有更好的链接。但这听起来像是您想要类似于单例的东西。或者一些创建任意数量实例的静态函数,以便您可以从静态成员函数中调用成员函数。 stackoverflow.com/questions/18997240/how-does-getinstance-work.
  • 如果db 是静态的,为什么Select 是非静态的?
  • @Dan 我试过这个,但它给了我其他错误:错误 LNK2001:未解析的外部符号“公共:静态类 CDatabase * CSchedulerDlg::db”

标签: c++ static-methods static-members


【解决方案1】:

为什么不能简单地为Select 函数提供一个对象?

void CSchedulerDlg::email(CString message)
{
    CSchedulerDlg aDlg;                                      // Now you have an object.

    CRecordset * emails = aDlg.Select("some SQL query", db); // This is now a valid call.
}

【讨论】:

    【解决方案2】:

    唯一的解决方法是使email 非静态,或将参数CSchedulerDlg& 添加到email

     static void email(CSchedulerDlg& dlg, CString message);
    

    并在dlg 对象上调用select。两种解决方案都非常相似。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多