c++ - 如何在 C++ 中引用类结构中的函数?

标签 c++ function class structure

我想使用 getSth 函数返回 main() 中的 struct aa 类型。 可以告诉我引用的方式吗?

//info.h
namespace nsp {
  class A {
    struct Info {
      struct aa {
        std::string str;
        int num;
        aa(): num(0) {}
      };
      std::vector<aa> aas;
      aa getSth();
    };
  };
}

//info.cpp
A::Info::aa A::Info::getSth() {
aa ret;
for(auto &tmp: aas) {
  if(ret.num < aas.num)
    ret.num = aas.num;
}
return ret;
}

// main.cpp
#include info.h
namepace nsp {
  class A;
}
int main()
{
  nsp::A *instance = new nsp::A();
  // How can I refer getSth using "instance"?
  .....
  return 0;
}

最佳答案

简单地说,你不能。您在类型为 Info 的嵌套结构中声明了 getSth,但没有声明该类型的任何数据成员。所以没有对象可以针对 nsp::A::Info::getSth 调用。

更糟糕的是,您将 A 声明为 class 并且没有提供访问说明符。类的成员都是private,没有访问说明符,所以getSth 不能在类外访问。如果您改为这样做:

class A {
  // other stuff; doesn't matter
  public:
  aa getSth();
};

那么,您可以像这样从 main 访问它:

int main()
{
  nsp::A *instance = new nsp::A();
  // now it's accessible
  instance->getSth();
  // deliberate memory leak to infuriate pedants
  return 0;
}

关于c++ - 如何在 C++ 中引用类结构中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51868841/

相关文章:

c++ - 对检索到的 vector 进行操作时出现段错误

c - 函数指针执行错误

c++ - 如何构造对象数组? C++

c++ - char* const args[] 定义

c++ - 可变参数函数是否已弃用?

仅当表达式的值不是 None 时才返回表达式的 Python 语法

function - 如何定义可变参数函数

c# - 返回多个结果的类方法(列表和多维数组)

c++ - MFC中可重用的后台线程

java - "if(<an integer> & 2)"是什么意思?