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/

相关文章:

function - 为什么要如此冗长地声明一个函数?

c++ - 我无法通过引用捕获传递 lambda

arrays - 如何构建对象层次结构,使所有名词都是单词但并非所有单词都是名词

c++ - 识别 libstdc++ 的版本

c++ - 无法使用 http_listener(C++ REST SDK)监听具有本地主机地址的特定端口号

c - C : warning: assignment from incompatible pointer type [-Wincompatible-pointer-types] 中的函数指针

c++ - 比较基类的 2 个派生对象

php - 是否应该为此使用 PHP 类?

c++ - CMake:使用 target_sources() 添加当前目录和子目录中的所有文件

c# - 在 x64 中从 C# 调用 C++ 代码,所有参数都移动 1