一个类名能成为数组的名称吗?

huangapple go评论70阅读模式
英文:

Can a class name be the name of an array?

问题

我在尝试在我的函数中使用这个数组时遇到了一个“类型名称未找到”的问题。

class dancer {
public:
    dancer();

void swap(int, int, dancer[]);

};


void dancer::swap(int num1, int num2, dancer[])
{
    int current = dancer[num1];
    dancer[num1] = dancer[num2];
    dancer[num2] = current;

}

我应该在我的任务中使用类名作为数组类型。我相信我在设置数组时出现了错误。错误出现在以下代码行:

int current = dancer[num1];
dancer[num1] = dancer[num2];
dancer[num2] = current;
英文:

I get a "type name not found" problem when I try to use this array for my function.

class dancer {
public:
    dancer();

void swap(int, int, dancer[]);

};


void dancer::swap(int num1, int num2, dancer[])
{
    int current = dancer[num1];
    dancer[num1] = dancer[num2];
    dancer[num2] = current;

}

I'm supposed to use the class name as my array type for my assignment. I believe I made an error on setting up the array. The error is at int current = dancer[num1];
dancer[num1] = dancer[num2];
dancer[num2] = current;

答案1

得分: 3

由于 `dancer` 是一个类型,它被解析为一个匿名方法参数,该参数是一个 `dancer` 对象的数组,而不是某种名为 'dancer' 的类型的数组。您必须为此参数命名:

void dancer::swap(int num1, int num2, dancer values[])

然后执行 `values[num1]` 与 `values[num2]` 的交换。

然而,您很可能在您的编程任务中基本上误解了某些内容。在这个情况下,将一个非静态类方法设计为以其自身类的其他实例的数组作为参数是没有逻辑意义的。

您应该重新阅读您编程任务的描述。您很可能遗漏了某个部分或细节;然而,上述内容解释了您的编译错误。
英文:
void dancer::swap(int num1, int num2, dancer[])

Since dancer is a type this gets parsed as an anonymous method parameter that's an array of dancer objects, and not as some array, of some type named 'dancer'. You have to name this parameter:

void dancer::swap(int num1, int num2, dancer values[])

and then some values[num1] with values[num2].

However it is fairly likely that you have fundamentally misunderstood something about your programming assignment. It makes no logical sense to have a non-static class method that takes, as a parameter, an array of other instances of its own class, for this purpose.

You should reread your programming task's description. You are likely missing some part or detail of it; however the above is the explanation for your compilation error.

huangapple
  • 本文由 发表于 2023年2月6日 05:26:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定