main.cpp

来自「C++ Source code from a tutorial」· C++ 代码 · 共 58 行

CPP
58
字号
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

class King {
protected:
    string CrownName;
public:
    virtual string &MyName() { return CrownName; }
};

class Prince : public King {
public:
    string School;
};

class Queen {
public:
    string Jurisdiction;
};

void KingInfo(King *inst) {
    cout << "=========" << endl;
    cout << inst->MyName() << endl;
    Prince *asPrince = dynamic_cast<Prince *>(inst);
    if (asPrince != 0) {
        cout << asPrince->School << endl;
    }
}

void KingInfoAsReference(King &inst) {
    cout << "=========" << endl;
    cout << inst.MyName() << endl;
    try {
        Prince &asPrince = dynamic_cast<Prince &>(inst);
        cout << asPrince.School << endl;
    }
    catch (...) {
    }
}

int main(int argc, char *argv[])
{
    Prince George;
    George.MyName() = "George I";
    George.School = "School of the Kings";
    KingInfoAsReference(George);
    
    King Henry;
    Henry.MyName() = "Henry II";
    KingInfoAsReference(Henry);

    system("PAUSE");	
    return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?