gpt4 book ai didi

c++ - 嵌套类作为C++中成员函数的参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:03:20 24 4
gpt4 key购买 nike

我正在集成某人的代码,其中包含一个 cpp 文件中的所有内容。主要代码如下:

class Outer
{
public:
struct Inner
{
struct In_inner
{
...
}
}
int func(Inner& inn, Inner::In_inner& in_inn)
{
...
}
}

要进行分离,我是否应该为“Inner”参数添加“Outer::”,如下所示?

在头文件中

class Outer
{
public:
struct Inner
{
struct In_inner
{
...
}
}
int func(Inner& inn, Inner::In_inner& in_inn);
}

在cpp文件中:

int Outer::func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn)
{
...
}

参数列表与声明有点不同,这对我来说听起来有点奇怪。另外,我可以再次将所有内容保存在同一个文件中,并将其作为头文件包含在内吗?

感谢任何评论!

最佳答案

int Outer::func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn)

是的。你已经正确地写了这个。如果您在类外定义它,则必须添加 Outer::


It sounds a bit weird to me that the parameter list is a bit different from the declaration

没关系。该函数是在类外部定义的。你已经不在类范围内了。因此它看起来有点不同。

但是如果你不想让它看起来不一样,那么你也可以在声明中写上Outer::,如下所示:

class Outer
{
public:
//...
int func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn);
};

这很好,并且可以工作,因为 Outer 是一个注入(inject)名称,它在类中也可用。

struct A
{
struct B {
struct C {};
};

B b1; //okay - as usual
A::B b2; //this is also okay - not so usual though

B::C c1; //okay - as usual
A::B::C c2; //this is also okay - not so usual though

A::A::A::A::A::A *pA; //this is very very unsual. But it is also okay!
};

最后一行没问题,因为名称 A 被注入(inject)到类 A 的定义中。因此它变得递归可用。

看到它编译得很好:

关于c++ - 嵌套类作为C++中成员函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6372732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com