为什么不能把"PURE"定义为一个const置0来标识纯虚类?

Why can't "PURE" be defined as a const set to 0 to identify pure virtual classes?

正在尝试将关键字 PURE 定义为设置为 0 的常量,以用作作为抽象数据类型的 类 的标识符。为什么这不会编译? "Essential C++, topic 1," 中的 Per Meyers 我宁愿使用 const 而不是 #define,像这样:

const int PURE = 0;
virtual void myFunction() = PURE;

唉,这会引发错误(在 Apple LLVM 7.0 和 gcc 上也是如此):

Initializer on function does not look like pure-specifier

示例如下,使用标记为 A、B 和 C 的三种技术;

1. const int PURE = 0 will not compile
2. #define PURE 0 compiles and runs fine
3. Simply setting function = 0 (Stroustrup) works fine.

现在使用const解决方案设置,因此无法编译。只需 comment/uncomment 第 4、5、11 和 12 行即可适当地检查三种不同的方法:

#include <iostream>
#include <string>

const int PURE = 0;                  // Case B
// #define PURE 0                       // Case C

const float PI = 3.14159;

class Shape {
public:
//    virtual float area() = 0;     // Case A: Compiles
    virtual float area() = PURE;    // Case B: This does not compile
                                    // Case C: Compiles
};
class Circle: public Shape {
public:
    Circle(float radius):radius_(radius) {}
    float area() { return PI * radius_ * radius_; }
private:
    float radius_;
};
class Rectangle : public Shape {
public:
    Rectangle(float base, float height):base_(base),height_(height) {}
    float area() { return base_ * height_; }
private:
    float base_;
    float height_;
};
int main(int argc, const char * argv[]) {
    Circle c(3);
    Rectangle r(3,5);

    std::cout << "Circle Area:    \t" << c.area() << std::endl;
    std::cout << "Rectangle Area: \t" << r.area() << std::endl;

    std::cout << std::endl;
    return 0;
}

语言语法说:

pure-specifier:
    = 0

也就是说,只允许使用令牌 = 0。您不能在此处放置 标识符

#define PURE 0 工作正常,因为宏替换发生在翻译之前。

只是为了补充@Brian 的回答和评论,恕我直言,这不是一个好主意。对于真正理解该语言的任何人来说,它 较少 可读,绝对没有增加任何价值,也没有任何用处。作为旁注,CS(尤其是函数式语言)中的 "pure" 根本不是 的同义词或等同于 C++ 中使用的 "pure virtual" (或其他语言中的 "abstract" 或 "interface" 之类的东西),因此将术语混淆作为潜在的额外缺点。

有些人曾经想从像 Pascal 这样的语言过渡到 "C",像这样:

#define BEGIN {
#define END   }
// etc...

很乱。这在任何语言中都是不好的做法。 在本例中,您使用的是 C++。所以使用C++语法。拥抱野兽之美:)

抱歉,评论太啰嗦了,所以不得不添加一个额外的答案,但@Brian 的原始答案既正确又简洁(并获得我的投票)。