5-1 CAT's Copy
指针+复制构造函数
#include <iostream>
using namespace std;
class CAT
{ public:
CAT(){
itsAge=new int;
*itsAge =5;
};
CAT(const CAT& c){
itsAge=new int;
*itsAge=*;
};
~CAT(){ delete itsAge; };
int GetAge() const { return *itsAge; }
void SetAge(int age){ *itsAge=age; }
protected:
int* itsAge;
};
5-2 A Fill in the blanks
模板类+异常处理+动态内存分配
#include <iostream>
using namespace std;
class IndexError{};
template <typename T>
class ARRAY
{
size_t m_size;
T *m_ptr;
public:
ARRAY(size_t size) : m_size(size)
{
m_ptr = new T[size];
memset(m_ptr, 0, size*sizeof(int));
}
~ARRAY()
{
delete[] m_ptr;
}
T& at(int index);
};
template <typename T>
T& ARRAY<T>::at(int index){
if(index<0||index>=m_size)
{
throw IndexError();
}
return m_ptr[index];
}
int main()
{
ARRAY<int> a(50);
int i;
cin >> i;
try
{
for(int j=0;j<i;j++)
(i) = j;
}
catch(IndexError e)
{
return 0;
}
return 0;
}
参考:///questions/7739502
5-3抽象类和纯虚函数的使用
抽象类+纯虚函数+动态内存分配+字符串
#include <iostream>
#include <cstring>
using namespace std;
class Base1 {
public:
//
virtual void Show()=0;
};
class Base2 {
protected:
char * _p;
Base2(const char *s)
{
_p = new char[strlen(s) + 1];
//下列语句将形参指向的字符串常量复制到该类的字符数组中
strcmp(_p,s);
}
~Base2() { delete [] _p; }
};
//Derived类公有继承Base1,私有继承Base2类
class Derived : public Base1,private Base2
{
public:
//以下构造函数调用Base2类构造函数
Derived(const char *s) : Base2(s)
{ }
void Show()
{ cout << _p << endl; }
};
int main()
{
Base1 *pb = new Derived("I'm a derived class.");
pb->Show();
delete pb;
return 0;
}
5-4运算符重载
重载输入输出和减法运算符
#include <iostream>
#include <cstring>
using namespace std;
class Circle{
private:
double rad;
double area;
friend istream& operator>>(istream&in, Circle &cl); //重载>>为Circle类的友元函数
friend ostream& operator<<(ostream&out, Circle &cl); //重载<<为Circle类的友元函数
public:
Circle(double r=0)
{
rad=r;
area=3.14*r*r;
}
double operator-(Circle &cl)//重载减号
{
return this->;//返回两个圆的面积差
}
};
istream& operator>>(istream&in, Circle &cl)
{
in>>; //从输入流中提取数据给圆的半径
=3.14**;
return in;
}
ostream& operator<<(ostream&out, Circle &cl)
{
out<<"rad="<<<<" area="<<<<endl; //输出圆的半径和面积,形如:rad=10 area=314
return out;
}
int main()
{
Circle c1,c2;
cin>>c1>>c2;
cout<<c1<<endl;
cout<<c2<<endl;
cout<<c2-c1<<endl;
return 0;
}
5-5 对象数组
对象数组+对象指针
#include <iostream>
using namespace std;
class Student
{public:
Student(int n,float s):num(n),score(s){};
//利用参数初始化表进行数据初始化
void display();
private:
int num;
float score;
};
void Student::display()
{cout<<num<<" "<<score<<endl;}
int main()
{
Student stud[5]={
Student(101,78.5),Student(102,85.5),Student(103,98.5),
Student(104,100.0),Student(105,95.5)}; //定义对象数组
Student *p=stud;
//定义对象指针指向对象数组
for(int i=0;i<3;i++,p+=2)//显示第1、3、5名学生信息
p->display();
return 0;
}
参考:///qq_52519691/article/details/118651714
5-6显式使用this指针
#include<iostream>
using namespace std;
class R{
int len,w;
public:
R(int len,int w);
int getArea();
};
R::R(int len,int w){
this->len=len;
this->w=w;
}
int R::getArea(){
return (this->len)*(this->w);
}
int main(){
R r1(2,5),r2(3,6);
cout<<"First Area is "<<()<<endl;
cout<<"Second Area is "<<()<<endl;
return 0;
}
5-7对象的动态创建
#include <iostream>
using namespace std;
class A{
int i;
public:
A(int k=0){
i=k;
}
void display(){
cout<<"i="<<i<<endl;
}
};
int main()
{
A *p=new A; //动态创建对象p
p->display();
delete p; //删除对象p
p=new A(8);
p->display();
delete p;
p=new A[3]; //p指向对象数组
A *q=p;
for(int i=0;i<3;i++){
(q++)->display(); //输出对象数组数据
}
delete []p;
//删除对象数组指针p
return 0;
}
5-8静态数据成员
#include<iostream>
using namespace std;
class Point{
double x,y;
static int count;//定义静态变量
public:
Point(double a=0,double b=0):x(a),y(b){
count++;
}
~Point(){
count--;
}
void show(){
cout<<"the number of Point is "<<count<<endl;
}
};
int Point::count=0;
int main(){
Point p1;
Point *p=new Point(1,2);
p->show();
delete p;
();
return 0;
}
5-9点类的定义和使用
#include <iostream>
using namespace std;
class Point
{
private://访问权限设置,私有权限
int x;//横坐标
int y;//纵坐标
public://访问权限设置,公有权限
//以下为构造函数,用参数a,b分别为横纵坐标进行初始化
Point(int a,int b)
{
x=a;
y=b;
}
//以下为拷贝构造函数,借用对象a_point完成初始化
Point(Point &a_point)
{
x=a_point.x;
y=a_point.y;
}
//以下为析构函数
~Point(){
cout<<"Deconstructed Point";
print();
}
//以下为输出点的信息的函数,要求在一行中输出点的坐标信息,形如:(横坐标,纵坐标)
void print()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
Point b_point(0,0);
b_point.print();
int a,b;
cin>>a>>b;
//从标准输入流中提取数值给a,b
Point c_point(a,b);
c_point.print();
return 0;
//主函数的返回语句
}
/*设输入为10 10,则本程序的运行结果为:
(0,0)
(10,10)
Deconstructed Point(10,10)
Deconstructed Point(0,0)
*/
5-10包含子对象的派生类构造函数
#include <iostream>
#include <string>
using namespace std;
class Student //声明基类
{
public: //公用部分
Student(int n,string nam) //基类构造函数
{
num=n;
name=nam;
}
void display() //输出基类数据成员
{cout<<"num:"<<num<<endl<<"name:"<<name<<endl;}
protected: //保护部分
int num;
string name;
};
class Student1: public Student //用public继承方式声明派生类student
{public:
Student1(int n,string nam,int n2,string mon,int a,string ad):Student(n,nam),monitor(n2,mon)
{
age=a; //在此处只对派生类新增的数据成员初始化
addr=ad;
}
void show( )
{
cout<<"This student is:"<<endl;
display(); //输出num和name
cout<<"age: "<<age<<endl;
cout<<"address: "<<addr<<endl<<endl;
}
void show_monitor() //输出子对象的数据成员
{
cout<<endl<<"Class monitor is:"<<endl;
(); //调用基类成员函数
}
private: //派生类的私有数据
Student monitor; //定义子对象(班长)
int age;
string addr;
};
int main( )
{
Student1 stud1(10010,"Wang-li",10001,"Li-sun",19,"115 Beijing Road,Shanghai");
( ); //输出第一个学生的数据
stud1.show_monitor(); //输出子对象的数据
return 0;
}
5-11多层派生时的构造函数
#include <iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(int n, string nam )
{
num=n;
name=nam;
}
void display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
}
protected:
int num;
string name;
};
class Student1: public Student
{
public:
Student1(int n1,string ss,int a):Student(n1,ss){age=a; }
void show( )
{
display();
cout<<"age: "<<age<<endl;
}
private:
int age;
};
class Student2:public Student1
{
public:
Student2(int n1,string ss,int a,int s):Student1(n1,ss,a)
{score=s;}
void show_all()
{show();
cout<<"score:"<<score<<endl;
}
private:
int score;
};
int main( )
{
Student2 stud(10010,"Li",17,89);
stud.show_all( );
return 0;
}
5-12 CPerson类对象数组
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
const int N=5;
class CPerson
{
char name[10];
char num[10];
public:
void get_data(const char* na,const char* nu)
{
strcpy(name,na);
strcpy(num,nu);}
void put_data(CPerson pn[N]);
};
void CPerson::put_data(CPerson pn[N])
{
int i;
for(i=0;i<N;i++)
{
(5);
cout<<pn[i].name;
(5);
cout<<pn[i].num<<endl;
}
}
int main()
{
char *na[5]={"li","zh","wu","xie","liu"};
char *nu[5]={"01","02","03","04","05"};
CPerson obj[5]; //对象数组
for(int i=0;i<5;i++)
obj[i].get_data(na[i],nu[i]);
CPerson *pt=obj;
pt->put_data(pt);
return 0;
}
5-13车辆类虚基类
#include <iostream>
using namespace std;
class vehicle //车辆类
{
private:
int MaxSpeed; //最大车速
int Weight; //车重
public:
vehicle(){MaxSpeed=0; Weight=0;}
virtual void Run() {cout<<"A vehicle is running!"<<endl;}
};
class bicycle : public vehicle
//自行车类
{
private:
int Height; //车高
public:
bicycle(){}
void Run() {cout<<"A bicycle is running!"<<endl;}
};
class motorcar : public vehicle
//机动车类
{
private:
int SeatNum; //乘人数
public:
motorcar(){}
void Run() {cout << "A motorcar is running!" << endl; }
};
class motorcycle: public bicycle,public motorcar
//摩托车类
{
public:
motorcycle (){}
void Run() {cout<<"A motorcycle is running!"<<endl;}
};
int main() {
motorcycle a;
();
return 0;
}
5-14本题目要求反序输出一行文字。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
string s;
//将该行输入保存到字符串s中
cin>>s;
i=();
while(i){
cout<<s[--i];
}
cout<<endl;
return 0;
}
5-15基于迭代器的折半查找
#include <iostream>
#include <vector>
using namespace std;
template <typename T, typename V>
T binarySearch(T begin, T end, const V v){
auto endOriginal = end;
while (begin!=end) {
auto mid=begin+(end-begin)/2;
if (*mid==v)
return mid;
else if (v < *mid)
end = mid;
else
begin=mid+1;
}
return endOriginal;
}
int main() {
vector<int> a {1,3,5,7,9,11,22,77,88,100,999,2132,6789};
int v;
cin >> v;
auto r = binarySearch((),(), v);
if (r==())
cout << "Not found." << endl;
else
cout << "Found: " << *r << endl;
return 0;
}
5-16爸爸、妈妈和我 - C/C++ 代码复用
#include <iostream>
using namespace std;
class Daddy {
public:
string sName;
void contribute()
{
cout << "Daddy " << sName << "'s duty: Driving & Building Shelter.\n";
}
};
class Mummy{
public:
string sName;
void contribute(){
cout << "Mummy " << sName << "'s duty: Prepare Food.\n";
}
};
class Brother {
public:
string sName;
void contribute(){
cout << "Brother " << sName << "'s duty: Joking.\n";
}
};
class MySelf {
public:
string sName;
void contribute(){
cout << sName << "'s duty: Taking Photos.\n";
}
};
class Family {
public:
Mummy m;
Daddy d;
Brother b;
MySelf s;
void outdoorPicnic(){
printf("---------outdoor picnic------------\n");
();
();
();
();
}
};
int main()
{
Family myFamily;
= "Emily"; //妈妈的姓名
();
= "Jack"; //爸爸的姓名
();
= "Tom"; //弟弟的姓名
();
= "Dora"; //我的姓名
();
();
return 0;
}
5-17动物和狗 - C/C++ 代码复用
#include <iostream>
using namespace std;
class Animal {
public:
int iFeetCount {0};
int iWeight {0};
Animal(){
cout << "Animal(), weight = " << iWeight << endl;
}
~Animal(){
cout << "~Animal(), weight = " << iWeight << endl;
}
};
class Dog : public Animal
{
public:
string sName;
Dog(const string name, int weight){
sName = name;
iFeetCount = 4;
iWeight=weight;
cout <<"Dog(), name = " << name << ", weight = " << iWeight << endl;
}
~Dog(){
cout <<"~Dog(), name = " << sName << ", weight = " << iWeight << endl;
}
};
int main()
{
Dog* d1 = new Dog("Bottle",3100);
delete d1;
cout << "---------------------------------------" << endl;
Dog* d2 = new Dog("Nauty",2312);
Animal* a2 = d2;
if (a2==d2){
cout << "Parent object is located at the beginning of sub object." << endl;
}
delete d2;
return 0;
}
5-18身份证解析 - C/C++ 容器与模板*
#include <iostream>
using namespace std;
int main()
{
string sId;
cin >>sId;
cout << "Area Number: " << (0,6) << endl;
cout << "Birth Date: " << (6,8) << endl;
return 0;
}
5-19年龄小的小朋友先吃糖 - C/C++ 容器与模板*
优先队列(priority_queue)容器+const
#include <iostream>
#include <queue>
using namespace std;
class Child {
public:
string sName;
int iAge;
bool operator>(const Child &c) const{
return (this->iAge>?true:false);
}
Child(string name, int age){
sName = name;
iAge=age;
}
};
int main()
{
priority_queue<Child,vector<Child>,greater<Child>> q;
(Child("Jack",7));
(Child("Tom",5));
(Child("Tiffany",9));
(Child("Alex",10));
(Child("Dick",4));
(Child("Jimmy",8));
while (!()){
auto x = ();
cout << << " at age " << << " get candy." << endl;
();
}
return 0;
}