19.1:
#include<cstdlib>
#include<iostream>
using namespace std;
void* operator new(size_t size)
{
if (void* mem = malloc(size))
{
return mem;
}
else
{
throw bad_alloc();
}
}
void operator delete(void* mem)noexcept
{
free(mem);
}
9.3:
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <typeinfo>
using namespace std;
class A
{
public:
A()
{
cout << "A()" << endl;
}
virtual ~A()
{
cout << "~A()" << endl;
}
};
class B :public A
{
public:
B()
{
cout << "B()" << endl;
}
virtual ~B()
{
cout << "~B()" << endl;
}
};
class C :public B
{
public:
C()
{
cout << "C()" << endl;
}
virtual ~C()
{
cout << "~C()" << endl;
}
};
class D :public B, public A
{
public:
D()
{
cout << "D()" << endl;
}
virtual ~D()
{
cout << "~D()" << endl;
}
};
int main(int argc, char** argv)
{
A* pa = new C;
if (B* pb = dynamic_cast<B*>(pa))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}//因为指针类型的转换失败返回为0可以使用条件中赋值判断
try
{
C& cp = dynamic_cast<C&>(*pa);//正确,*pa的类型是C
cout << "cp" << endl;
}
catch (std::bad_cast e)
{
cout << e.what() << endl;
}//引用类型失败返回的是bad_cast
B* pbb = new B;
if (C* pc = dynamic_cast<C*>(pbb))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
A* paa = new D;
if (B* pc = dynamic_cast<C*>(paa))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
cin.get();
return 0;
}
19.6:
#include<iostream>
using namespace std;
class Base{
virtual void print()
{}
};
class Derived:public Base{};
int main()
{
Derived* dp = new Derived;
Base* bp = dp;
bool b = (typeid(*dp)== typeid(*bp));
cout << b << endl;
}
19.9:
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <typeinfo>
using namespace std;
int main(int argc, char** argv)
{
int arr[41];
double i = 6.23;
vector<int> vec1;
int* p = arr;
cout << typeid(arr).name() << endl;
cout << typeid(i).name() << endl;
cout << typeid(vec1).name() << endl;
cout << typeid(p).name() << endl;
cin.get();
return 0;
}
19.12:
#include <string>
#include <iostream>
class Screen {
public:
using pos = std::string::size_type;
static const std::string Screen::* data() { return &Screen::contents; }
static const pos Screen::* pcursor() { return &Screen::cursor; }
Screen() = default;
Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht* wd, c) { }
char get() const { return contents[cursor]; }
char get(pos r, pos c) const { return contents[r * width + c]; }
private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
};
int main()
{
// const std::string Screen::*pdata;
// pdata = &Screen::contents;
// auto pdata = &