[英]How can I refer to the function in structure of class in C++?
I'd like to use the getSth function which returns struct aa
type in main()
. 我想使用getSth函数,该函数在
main()
返回struct aa
类型。 Would you let me know the way to refer it? 您能让我知道引用它的方式吗?
//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;
}
Quite simply put, you can't . 简而言之, 你不能 。 You declared
getSth
inside a nested struct of type Info
but didn't declare any data members of that type. 您在
Info
类型的嵌套结构中声明了getSth
,但未声明该类型的任何数据成员。 So there's no object to call nsp::A::Info::getSth
against. 因此,没有对象可以调用
nsp::A::Info::getSth
。
What's worse, you declared A
as a class
and didn't provide an access specifier. 更糟糕的是,您将
A
声明为class
,但没有提供访问说明符。 A class's members are all private
without an access specifier, so getSth
can't be accessed outside the class. 类的成员都是
private
没有访问说明符,因此无法在类外部访问getSth
。 If you had done it this way instead: 如果您是用这种方式完成的:
class A {
// other stuff; doesn't matter
public:
aa getSth();
};
well then, you could have accessed it from main
like this: 那么,您可以像这样从
main
访问它:
int main()
{
nsp::A *instance = new nsp::A();
// now it's accessible
instance->getSth();
// deliberate memory leak to infuriate pedants
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.