我想使用 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/