Pho*_*ong 3 c++ typedef overloading
为什么我不能在程序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);
print(b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
计划2:
#include <iostream>
typedef struct{int a;} s1;
typedef struct{int a;} 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;
}
Run Code Online (Sandbox Code Playgroud)
这是从模板类重现的错误,如何验证两个模板参数是否来自同一类型(在程序1的情况下)
Joh*_*ica 10
Typedef不定义新类型,它们只是为现有类型创建别名.在你的第一个程序中s1,s2它们都是别名int.在你的第二个程序中,它们是两个不同结构的别名,结构恰好相同.
您可以为这两个结构指定名称,这样可以更清楚:
// Semantically identical to program 2
typedef struct a {int a;} s1;
typedef struct b {int a;} s2;
Run Code Online (Sandbox Code Playgroud)
另一方面,如果你为同一类型制作别名,那么第二个程序将像第一个程序一样失败:
// Different from program 2. This will draw a compile error.
struct s {int a;};
typedef struct s s1;
typedef struct s s2;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1507 次 |
| 最近记录: |