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

How can I refer to the function in structure of class in C++?

本文关键字:结构 函数 引用 C++      更新时间:2023-10-16

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