参考资料:《C++Primer习题集(第5版)》
目的:理解每个print函数的机制。
话说这感觉有点儿像打草稿。。。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
//class Base {
// public:
// string name() const {return basename;}
// virtual void print(ostream &os) {os << basename;}
// private:
// string basename = "xyz";
//};
/*
class Derived : public Base {
public:
void print(ostream &os) {os << "xyz" << endl; print(os); os << " " << mem;}//没有声明Derived是从Base派生过来的;
private:
int mem;
};
*/
class Base {
public:
Base(string s) : basename(s) {}//初始化构造器;
string name() const {return basename;}
virtual void print(ostream &os) {os << basename << endl;}
private:
string basename;
};
class Derived : public Base {
public:
Derived(string s, int ival) : Base(s), mem(ival) {}//调用基类的构造函数;
void print() {Base::print(cout); cout << mem << endl;}//声明Derived是从Base派生过来的;
private:
int mem;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
Base *b = new Base("ab");
b -> print(cout);//xyz;
Derived *d = new Derived("cd", 12);
d -> print();
delete b;
delete d;
return 0;
}