c – 函数重载时的Typedef编译错误
发布时间:2020-12-16 10:16:22 所属栏目:百科 来源:网络整理
导读:为什么我不能在程序2工作正常时编译程序1?为什么它的行为不同? 计划1: #include iostreamtypedef int s1;typedef int s2;void print(s1 a){ std::cout "s1n"; }void print(s2 a){ std::cout "s2n"; }int main() { s1 a; s2 b; print(a); print(b); retu
为什么我不能在程序2工作正常时编译程序1?为什么它的行为不同?
计划1: #include <iostream> typedef int s1; typedef int s2; void print(s1 a){ std::cout << "s1n"; } void print(s2 a){ std::cout << "s2n"; } int main() { s1 a; s2 b; print(a); print(b); return 0; } 计划2: #include <iostream> typedef struct{int a;} s1; typedef struct{int a;} s2; void print(s1 a){ std::cout << "s1n"; } void print(s2 a){ std::cout << "s2n"; } int main() { s1 a; s2 b; print(a); print(b); return 0; } 这是从模板类重现的错误,如何验证两个模板参数是否来自同一类型(在程序1的情况下) 解决方法
Typedef不定义新类型,它们只是为现有类型创建别名.在你的第一个程序中,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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |