如何在C++中引用类结构中的函数?
How can I refer to the function in structure of class in C++?
我想使用 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++ 编辑:修复LNK2019错误
- 如何将值从外部传递到结构函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C++结构函数的多个定义
- C++ 另一个标头中的结构函数给出"missing type specifier"
- 如何在C中找到结构/函数的父头文件
- C++二进制文件到结构函数
- C++ 将结构函数作为继承结构中函数的参数传递
- 如何在 main 之外的类中使用结构函数
- 在类中使用结构函数,在基类 c++ 中使用变量
- C++ 结构函数体调用另一个结构函数,同一个模块
- 是存储在对象中的类/结构函数
- Eclipse CDT 在从 std::map 访问时无法解析结构函数
- C++模板自身名称作为模板模板参数在同一模板结构函数内传递
- 如何使用真正的字符串类型来表示类结构函数中的字符串