【问题标题】:Is it legal C++ to use a typedef in a method declaration but the canonical type in the method definition?在方法声明中使用 typedef 但在方法定义中使用规范类型是否合法 C++?
【发布时间】:2009-08-25 15:53:20
【问题描述】:

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++ 吗?其他编译器可能会接受它吗?

【问题讨论】:

    标签: c++ g++ standards typedef standards-compliance


    【解决方案1】:

    是的,这是合法的:

    7.1.3 typedef 说明符

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

    【讨论】:

    • 这是对的,但我认为“另一种类型的同义词”和/或“不引入新类型”是应该强调的短语。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      是的,这是合法的。

      这是值得怀疑的,因为声明和定义如何匹配已经不明显了,但如果你有充分的理由,你可以做到。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多