Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88272
  • 博文数量: 60
  • 博客积分: 4002
  • 博客等级: 中校
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-17 18:11
文章分类

全部博文(60)

文章存档

2011年(60)

我的朋友

分类: C/C++

2011-03-30 22:35:36

Abstract classes (C++ only)

An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.

class AB {
public:
virtual void f() = 0;
};




Function AB::f is a pure virtual function. A function declaration cannot have both a pure specifier and a definition.

You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class. You can, however, declare pointers and references to an abstract class.

Virtual member functions are inherited. A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class.
For example:

class AB {
public:
virtual void f() = 0;
};

class D2 : public AB {
void g();
};

int main() {
D2 d;
}



The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f()from AB. The compiler will allow the declaration of object d if you define function D2::g().

Note that you can derive an abstract class from a non-abstract class, and you can override a non-pure virtual function with a pure virtual function.

A base class containing one or more pure virtual member functions is called an abstract class.

  • The members of a class declared with the keyword class are private by default. A class is inherited privately by default.
  • The members of a class declared with the keyword struct are public by default. A structure is inherited publicly by default.
  • The members of a union (declared with the keyword union) are public by default. A union cannot be used as a base class in derivation.
阅读(1190) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~