【问题标题】:call to non-static member function without an object argument when call my Struct in function that use in std::async在 std::async 中使用的函数中调用我的 Struct 时调用不带对象参数的非静态成员函数
【发布时间】:2021-11-08 08:25:47
【问题描述】:

我有这个代码:

#include <future>
#include <iostream>

struct Status
{
    std::string Available;
    std::string Connected;
    std::string DisConnected;
};

class Test
{
 public:
   Test();

   Status &status()
   {
       return _status;
   }
   void setStatus(const Status &newStatus)
   {
       _status = newStatus;
   }

   std::string show()
   {

       return Status::Available;
   }

private:
    Status _status ;
};



int main()
{

    Test tst;

    auto value= std::async([](std::string str) { return str;} ,tst.show());

    std::cout <<value.get();


    return 0;
}

当我编译它时,我得到了这个错误:

非法引用非静态成员'Status::Available'

我不知道我应该如何解决这个问题,但是因为我在std::async 中使用了该功能而发生这种情况。我也不知道为什么会这样。

【问题讨论】:

  • “当我调用 getter 函数时”是什么意思?显示的一行代码没有携带任何有用的信息。它出现在哪里?一些功能?什么方法?您能否按照 Stackoverflow 的说明创建一个每个人都可以剪切/粘贴的minimal reproducible example完全如图所示 到一个空文件中,然后尝试编译并重现您的编译错误?
  • @SamVarshavchik 我编辑我的问题

标签: c++ c++11 static c++17 c++14


【解决方案1】:

您需要将其更改为 _status.Available。 您正在尝试引用 Status 结构,而不是该结构的实例。

【讨论】:

  • 不知道status,想从status函数中获取怎么办?或类似的东西我的问题是我不知道它是否可用我想得到它并将它发送到std::async
  • 您的问题不清楚。如果您想动态分配 Test 类的实例,您可以使用 new 运算符执行此操作,您可以查看here 了解更多信息。此外,如果您将 Status 设置为布尔值,您可以将它们评估为 True/False。我不完全确定您要在这里做什么。对于使用 std::async 的示例,您可以查看 here
  • 我想在另一个地方设置我的状态,并在它改变时获取它并将其发送到线程。
  • 我相信对于这种处理,你必须在你的线程中循环,不断检查值的变化。
猜你喜欢
  • 2014-11-28
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多