0 c++ structure class function
我想使用返回struct aa类型的getSth函数main().你能让我知道推荐的方式吗?
//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;
}
Run Code Online (Sandbox Code Playgroud)
很简单,你不能.您getSth在类型的嵌套结构中Info声明但未声明该类型的任何数据成员.所以没有反对的对象nsp::A::Info::getSth.
更糟糕的是,您声明A为a class并且未提供访问说明符.类的成员都private没有访问说明符,因此getSth无法在类外访问.如果你这样做了:
class A {
// other stuff; doesn't matter
public:
aa getSth();
};
Run Code Online (Sandbox Code Playgroud)
那么,你可以从main这样访问它:
int main()
{
nsp::A *instance = new nsp::A();
// now it's accessible
instance->getSth();
// deliberate memory leak to infuriate pedants
return 0;
}
Run Code Online (Sandbox Code Playgroud)