简体   繁体   English

一些设计模式代码中的奇怪语法:解释?

[英]Strange syntax in some Design Pattern code: explanation?

OK, I ran into this today, when the TI TMS470 C++ compiler refused to take it. 好的,今天我遇到了这个问题,那时TI TMS470 C ++编译器拒绝接受它。

This comes from the Silver version of the C++ translation of the "Head First Design Patterns" example code. 这来自“Head First Design Patterns”示例代码的C ++版本的Silver版本。

class foo {
   ...
protected:
   virtual ~foo() = 0 {};  // compiler barfs on this line
};

The compiler refused to accept the combination of "= 0" (pure virtual) and "{}" (I'm guessing that this is to let a derived class throw the destructor up anyway. 编译器拒绝接受“= 0”(纯虚拟)和“{}”的组合(我猜这是为了让派生类无论如何都要抛出析构函数。

What exactly are they trying to do with that line, is it really legal C++, and how critical is it? 究竟他们试图用这条线做什么,它真的是合法的C ++,它有多重要?

It is not legal C++. 它不是合法的C ++。 Pure virtual function can have a body, but the definition has to be made out-of-class. 纯虚函数可以有一个主体,但定义必须是在课外进行的。

In this particular case (the function is a destructor), the function must have a body if the class is used anywhere in the program (ie if it is used as a base class somewhere, since this is the only way one can use an abstract class). 在这种特殊情况下(函数是析构函数),如果在程序中的任何地方使用类,函数必须有一个主体(即,如果它在某个地方用作基类,因为这是可以使用抽象的唯一方法类)。

The proper way do define the whole thing is as follows 确定整个事情的正确方法如下

class foo {
   ...
protected:
   virtual ~foo() = 0;
};

inline foo::~foo()
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM