C++ 函数重载时Typedef编译错误
当程序2运行良好时,为什么我不能编译程序1?为什么它的行为不同 方案1:C++ 函数重载时Typedef编译错误,c++,overloading,typedef,C++,Overloading,Typedef,当程序2运行良好时,为什么我不能编译程序1?为什么它的行为不同 方案1: #include <iostream> typedef int s1; typedef int s2; void print(s1 a){ std::cout << "s1\n"; } void print(s2 a){ std::cout << "s2\n"; } int main() { s1 a; s2 b; print(a);
#include <iostream>
typedef int s1;
typedef int s2;
void print(s1 a){ std::cout << "s1\n"; }
void print(s2 a){ std::cout << "s2\n"; }
int main() {
s1 a;
s2 b;
print(a);
print(b);
return 0;
}
#包括
typedef int s1;
typedef int s2;
void print(s1a){std::coutint
是一种基本类型:无论在哪里使用它,它都会引用完全相同的东西-anint
struct{int a;}
不是一个基本类型-每次定义struct{int a;}
时,您都在创建一个新类型-因此,在Program 2案例中,s1
和s2
被认为是不同的
例如,考虑以下内容:
typedef struct{int count;} apples;
typedef struct{int count;} airplanes;
苹果和飞机是一回事吗?可能不是。但它们的计数都是数字。因此为什么int
是一致的,而structs
不是-int
没有上下文关联,structs是
typedef
实际上并不生成任何新类型-它只在另一个名称下为类型添加别名
因此,程序1和程序2之间的区别在于,在程序1中,您试图使用(就编译器而言)完全相同的签名定义函数的两个版本:print(int)
。在程序2中,您定义了两个不同的签名:print([first struct type])
和print([second struct type])
类型定义不定义新类型,它们只是为现有类型创建别名。在第一个程序中,s1
和s2
都是int
的别名。在第二个程序中,它们是两个不同结构的别名,恰好结构相同
您可以为这两个结构指定名称,这将使这一点更加清楚:
// Semantically identical to program 2
typedef struct a {int a;} s1;
typedef struct b {int a;} s2;
另一方面,如果将它们作为同一类型的别名,则第二个程序将与第一个程序一样失败:
// Different from program 2. This will draw a compile error.
struct s {int a;};
typedef struct s s1;
typedef struct s s2;
不同之处在于,在程序1中,s1
和s2
是相同类型的别名,而在程序2中它们是不同类型的别名。即使使用不同的类型名称生成签名,也不能用相同的签名定义函数的两个重载。typedef
不会创建新类型。struc第二代码中有两种不同类型,但在第一种情况下不是这样的。对于它来说,在C++中不需要结构和类中的Type,如果你写的是“代码>结构S1{int A;},你不需要TyBuffF。;
”。但是,当您省略如图所示的结构标记时,您确实需要typedef为其命名。(没有typedef,您定义了一个匿名结构类型的变量-至少在C中是这样。)@Jonathan:我的意思是他因此会将名称移到前面。但无论如何,这可能是为了手头的问题。
// Different from program 2. This will draw a compile error.
struct s {int a;};
typedef struct s s1;
typedef struct s s2;