为什么要在类对象的声明中写一个“类”?

我通常不会这样写,但我见过一个代码库几乎无处不在,例如:

class prettyClass
{
    // just class stuff
};

int main()
{
    class prettyClass obj; // class?
    return 0;
}

回答

在 C 中,结构的标签与其他标识符位于不同的命名空间中。因此,除非引入别名,否则他们必须struct T为类型名称编写。在 C++ 中(其中classstruct具有相同的基本概念),它被制作成标签被自动引入为常规标识符。

但是,必须考虑 C 中的一种行为。你可以有这样的事情:

struct prettyThing
{
  // data
};

void prettyThing();

由于名称空间不同,因此没有歧义。所以 C++ 保留了这种行为。还可以有:

class prettyThing
{
   // members
};

void prettyThing();

没有歧义,类名被另一个标识符隐藏。它只能通过精心设计的类型说明符访问,即class prettyThing. 这是为什么人们可以像您看到的那样编写声明的一个实际原因。这不是学术性的,请考虑 POSIXstatstruct statpair。

但是……除非您与最初以 C 概念编写的 C 代码交互,否则没有理由以这种方式编写新的 C++ 代码。

人们可能想知道为什么对于用 声明的类型不保持相同,而对于用 声明的类型struct根本不允许使用class。要理解这一点,最好重申并记住classes 和structures 在 C++ 中实际上是同一个东西(除了默认访问说明符)。以下是所有有效的 C++:

struct thing1; // forward declare

class thing1 {
  // define
};

struct thing2 {
   // define
};

class thing2 object;

任何一个关键字都可以在详细类型说明符中使用,它们在标准 C++ 1中完全可以互换。


1 - 不过,微软 ABI 在这里表现得有点古怪。

  • @A.Ocannaille - We'll have to agree to disagree. There's plenty of questions flowing in by people thinking a struct has its own category in type system when it doesn't. The "imperfect" term does far more harm than a sentence that blows one's expectations out the water.

以上是为什么要在类对象的声明中写一个“类”?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>