C++ 是否合法?在方法声明中使用 typedef 但在方法定义中使用规范类型?

发布于 2024-08-03 07:32:59 字数 320 浏览 1 评论 0原文

GNU C++ (g++ -pedantic -Wall) 接受这一点:

typedef int MyInt;

class Test
{
public:
    MyInt foo();
    void bar(MyInt baz);
}; 

int Test::foo()
{
    return 10;
}

void Test::bar(int baz)
{
}

int main(void)
{
    Test t;
    t.bar(t.foo());
    return 0;
}

它是合法的 C++ 吗?其他编译器可能接受它吗?

The GNU C++ (g++ -pedantic -Wall) accepts this:

typedef int MyInt;

class Test
{
public:
    MyInt foo();
    void bar(MyInt baz);
}; 

int Test::foo()
{
    return 10;
}

void Test::bar(int baz)
{
}

int main(void)
{
    Test t;
    t.bar(t.foo());
    return 0;
}

Is it legal C++? Are other compilers likely to accept it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

彼岸花似海 2024-08-10 07:32:59

是的,这是合法的:

7.1.3 typedef 说明符

使用 typedef 声明的名称
说明符变成类型定义名称。
在其声明的范围内,
typedef-name 语法上
相当于关键字并为其命名
与标识符相关联的类型
第8条A中描述的方式
因此 typedef-name 是以下的同义词
另一种类型。 typedef-name 没有
以类的方式引入新类型
声明 (9.1) 或枚举声明
是的。

Yes it is legal:

7.1.3 The typedef specifier

A name declared with the typedef
specifier becomes a typedef-name.
Within the scope of its declaration, a
typedef-name is syntactically
equivalent to a keyword and names the
type associated with the identifier in
the way described in clause 8. A
typedef-name is thus a synonym for
another type. A typedef-name does not
introduce a new type the way a class
declaration (9.1) or enum declaration
does.

じее 2024-08-10 07:32:59

无论是否合法,这都不是最佳做法。 Typedef 的存在使得您可以更改基本类型并将其反映在您的整个代码中,如果您这样做,您会突然发现您的程序不再编译。

Regardless of whether it is legal it's not the best of practices. Typedefs exist so you can change the base type and have it reflected all over your code and if you ever do so you'll find suddenly your program doesn't compile anymore.

橘亓 2024-08-10 07:32:59

是的,这是合法的。

这是有问题的,因为声明和定义如何匹配不再明显,但如果你有充分的理由,你可以这样做。

Yes, it is legal.

It is questionable, since it's not obvious anymore how declaration and definition match, but if you have a good reason, you can do it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文