参数列表中的类型定义 [英] type definition in parameter list

查看:67
本文介绍了参数列表中的类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int func(struct x{int a;}y);
int main()
{

}

上面的代码在c ++中给出了以下错误
错误:可能无法在参数类型中定义类型
虽然它在c中可以正常运行并带有警告,但c类型的方法可以在参数列表中定义
因此,以下代码应在c中给出重新定义错误

The above code gives following error in c++
error: types may not be defined in parameter types
while its run fine in c with warning,means in c type may be define in parameter list
thus the following code should give redefination error in c

int func(int a,int a);
int main()
{

}

怀疑:为什么上述代码在c ++中给出错误
错误:多个参数名为

Doubt:why the above code giving error in c++
error:Multiple parameter named a

推荐答案

使参数具有相同的名称两次是错误的,因为参数名称在其参数列表中.我认为很明显,让两个参数具有相同的名称没有用吗?

It's an error to have a parameter have the same name twice, because parameter names are in scope in their parameter list. I think it's obvious that having two parameters have the same name isn't useful?

// Explain why you want to have them say "int a, int a"
int func(int a, int b);

在C语言中,可以在参数类型列表中定义结构类型的内容.标签标识符具有原型范围或块范围(当函数是定义时),并且没有链接,这意味着它不同于在原型或块之外声明的结构(标签标识符具有文件范围).您不能从其体内递归调用此类函数.

In C it is allowed to define the content of struct types in parameter type lists. The tag identifier either has prototype scope or block scope (when the function is a definition) and has no linkage, which means it is different from a struct declared outside the prototype or blocks, whose tag identifier has file scope. You cannot call such a function except recursively from inside its body.

int func(struct x{int a;} y) { 
  func(y); // fine (the call, not the endless recursion)
}

请注意,这仅适用于在定义了 func 的同一个翻译单元中发生的调用.如果在另一个翻译单元中按如下方式声明函数和结构,那完全可以,并且该函数将是可调用的(您需要确保上面的声明不可见,否则会发生冲突,因为两点的 x 表示不同的类型).

Note that this applies only for calls that happen in the same translation unit that func is defined in. If in another translation unit you declare the function and struct as follows, that is entirely fine, and the function will be callable (you need to make sure the above declaration is not visible, otherwise you get a clash, because x at both points denotes a different type).

struct x {int a;};
int func(struct x y);

在两个翻译单元中,即使 x 是不同的类型(因为它们是不同的翻译单元),这些类型也是 compatible ,这是唯一重要的用于参数类型.

In both translation units, even though x is a different type (because they are different translation units), the types are compatible, which is the only thing that matters for parameter types.

您不仅可以在参数列表中定义结构,还可以在函数的返回类型部分中定义

You cannot only define the struct in a parameter list, but also in the return type section of a function

struct x {int a;} func(void) {
  return (struct x){ 0 };
}

这也仅适用于C.C++中不允许这种情况.

This too applies only to C. No such thing is allowed in C++.

这篇关于参数列表中的类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆