【问题标题】:unknown type name 'class'未知类型名称“类”
【发布时间】:2016-10-28 18:44:15
【问题描述】:

我正在为几个几何形状创建一个小型库。这样做,我将原型写入shapes.h 文件,并将方法写入shapes.cpp 文件。 这是标题:

#ifndef __shapeslib
#define __shapeslib

class Shape{
protected:
  struct dimensions{
    double heigth;
    double width;
  };
  double radius;                        // for circle class to be inherited

public:
  Shape(double heigth, double width);   // Constructor
  Shape(const Shape & shape);           // copy constructor for class
  ~Shape();                             // Destructor

  virtual double area(double heigth, double width);
  virtual double perimeter(double heigth, double width);
  void height();
  void width();
  double rotate(double heigth, double width);
};

但在 Atom 软件中保存文件时,class Shape{ 行出现这两个错误

unknown type name 'class'

expected ';' after top level declarator

我阅读了here,这可能是因为我使用 C 而不是 C++ 进行编译。我真的不知道如何避免这种情况(仍然是初学者)。

我还尝试将文件名从 .h 更改为 .hpp 并且似乎有效。不幸的是,我必须有一个.h 头文件。

非常感谢任何反馈。 谢谢大家。

【问题讨论】:

  • C 中没有class
  • 也许 Atom 使用文件扩展名错误地自动检测语言,您需要弄清楚如何让它假设 .h 文件是 C++ 而不是 C? This 似乎对你有所帮助。
  • 这不是问题,但是包含两个连续下划线 (__shapeslib) 的名称和以下划线后跟一个大写字母的名称保留供实现使用。不要使用它们。
  • 当您在头文件的第一个标记上出现错误时,错误可能在您的翻译单元编译中 shape.h 之前的头文件中。您可以使用g++ -E 来检查预处理的结果。也许缺少;
  • @MattiaPaterna - 包含警卫是一件好事。使用保留名称来实现它们不是。

标签: c++ class header-files atom-editor


【解决方案1】:

实际上,似乎 Atom 会自动将 .h 头文件检测为 C 语言文件。 here 解释了解决此问题的几种方法。我尝试使用 ctrl+shift+L 从 C 手动切换到 C++,现在我没有任何错误。我可能在class这个词旁边还有一个红点,并显示这样的错误:

expected ';' after top level declarator

但代码运行正常。

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 1970-01-01
    • 2014-11-19
    • 2018-10-27
    • 2016-09-16
    • 2012-04-03
    • 2017-01-09
    • 2015-01-25
    相关资源
    最近更新 更多