C++面向对象
- 面向对象最主要的2个主要特质是:继承与多态
漫游
- 默认情况下member function的解析实在编译时动态进行。如果需要其在运行时动态进行,我们需要在其声明前加入virtual关键字。
- 如果有一个类A,是类B的基类,则在定义出一个类B的对象时,A与B的构造函数与析构函数都会被执行(执行次序颠倒)。
- 如果有多级派生,则会依次调用基类的构造与析构函数,直到没有基类为止
static成员函数无法被声明为虚函数
LibMat.h
#ifndef LIBMAT_H #define LIBMAT_H #include <cstdlib> #include <string> #include <iostream> #include <ostream> #include <assert.h> #include <time.h> #include <algorithm> #include <functional> #include <iterator> #include <fstream> #include <vector> using namespace std; class LibMat { public: LibMat() { cout << "LibMat::LibMat() default constructor!" << endl; } // 对于经过virtual修饰的member function,会在runtime进行动态解析 virtual ~LibMat() { cout << "LibMat::~LibMat() default destructor!" << endl; } virtual void print() const { cout << "LibMat::print() -- I am a LibMat object!" << endl; } }; #endif
Book.h
#ifndef BOOK_H #define BOOK_H #include "LibMat.h" using namespace std; class Book : public LibMat { public: Book(const string &title, const string& author) :_title(title), _author(author) { cout << "Book::Book( " << _title << ", " << _author << " ) constructor" << endl; } virtual ~Book() { cout << "Book::~Book() default destructor!" << endl; } virtual void print() { cout << "Book:print() -- I am a Book object." << endl << "\tMy title is: " << _title << endl << "\tMy author is: " << _author << endl; } const string &title() const { return _title; } const string &author() const { return _author; } protected: string _title; string _author; }; #endif
AudioBook.h
#ifndef AUDIOBOOK_H #define AUDIOBOOK_H #include "Book.h" using namespace std; class AudioBook : public Book { public: AudioBook(const string &title, const string& author, const string& narrator) :Book(title, author), _narrator(narrator) { cout << "AudioBook::AudioBook( " << _title << ", " << _author << ", " << _narrator << " ) constructor" << endl; } virtual ~AudioBook() { cout << "AudioBook::~AudioBook() default destructor!" << endl; } virtual void print() { cout << "AudioBook:print() -- I am a AudioBook object." << endl << "\t\tMy title is: " << _title << endl << "\t\tMy author is: " << _author << endl << "\t\tMy narrator is: " << _narrator << endl; } const string &narrator() const { return _narrator; } protected: string _narrator; }; #endif
main.cpp
#include "AudioBook.h" using namespace std; typedef long long ll; // 当定义一个派生对象时,基类和派生类的constructor都会被执行,destructor也都会被执行(但是次序颠倒) void testClass() { //LibMat mat; //mat.print(); //Book book("book1", "author1"); //book.print(); AudioBook abook("book2", "author2", "narrator2"); abook.print(); } int main() { // 按照时间来初始化种子,保证每次结果不一样 srand( (int)time(0) ); //cout << rand() << endl; testClass(); system("pause"); return 0; }
其他
- 对于static类型的类成员函数,需要在类外对其声明(一般在h文件中),再对其进行定义(可以在cpp文件或者h文件中均可),否则会出现
unresolved externals
之类的错误,可以参考这个帖子:https://bbs.csdn.net/topics/320269587