gpt4 book ai didi

c++ - 函数重载时的 Typedef 编译错误

转载 作者:太空狗 更新时间:2023-10-29 19:47:18 24 4
gpt4 key购买 nike

当程序 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;
}

程序 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;
}

这是一个从模板类重现的错误,我如何验证两个模板参数是否来自同一类型(在程序 1 的情况下)

最佳答案

Typedef 不定义新类型,它们只是为现有类型创建别名。在您的第一个程序中,s1s2 都是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;

关于c++ - 函数重载时的 Typedef 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2339226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com