C++ primer plus(第6版)中文版编程练习答案第18章
- 格式:docx
- 大小:14.16 KB
- 文档页数:6
1、
//init.cpp
#include
#include
using namespace std;
template
T average_list(initializer_list
int main()
{
auto q = average_list({ 15.4, 10.7, 9.0 });
cout<< q < cout< auto ad = average_list cout<< ad < system("pause"); return 0; } template T average_list(initializer_list { T sum = 0; inti = 0; for (auto p = il.begin(); p != il.end(); p++, i++) sum += *p; return sum / i; } 2、 //cpmv.h #ifndef CPMV_H_ #define CPMV_H_ #include #include using namespace std; classCpmv { public: struct Info { stringqcode; stringzcode; }; private: Info *pi; public: Cpmv(); Cpmv(string q, string z); Cpmv(constCpmv&cp); Cpmv(Cpmv&&mv); ~Cpmv(); Cpmv&operator=(constCpmv&cp); Cpmv&operator=(Cpmv&&mv); Cpmv operator+(constCpmv&obj)const; void Display()const; }; Cpmv::Cpmv() { pi = new Info; pi->qcode = "Nothing"; pi->zcode = "Nothing"; cout<< "Default construct called: \n"; Display(); } Cpmv::Cpmv(string q, string z) { pi = new Info; cout<< "String construct called: \n"; pi->qcode = q; pi->zcode = z; Display(); } Cpmv::Cpmv(constCpmv&cp) { pi = new Info; cout<< "Copy construct called: \n"; pi->qcode = cp.pi->qcode; pi->zcode = cp.pi->zcode; Display(); } Cpmv::Cpmv(Cpmv&&mv) { pi = new Info; cout<< "Move construct called: \n"; pi->qcode = mv.pi->qcode; pi->zcode = mv.pi->zcode; mv.pi->qcode = "Nothing"; mv.pi->zcode = "Nothing"; Display(); } Cpmv::~Cpmv() { cout<< "Destruct called! \n"; delete pi; } Cpmv&Cpmv::operator=(constCpmv&cp) { cout<< "Copy assignment operator called: \n"; if (this == &cp) return *this; pi->qcode = cp.pi->qcode; pi->zcode = cp.pi->zcode; Display(); return *this; } Cpmv&Cpmv::operator=(Cpmv&&mv) { cout<< "Move assignment operator called: \n"; if (this == &mv) return *this; pi->qcode = mv.pi->qcode; pi->zcode = mv.pi->zcode; mv.pi->qcode = "Nothing"; mv.pi->zcode = "Nothing"; Display(); return *this; } CpmvCpmv::operator+(constCpmv&obj)const { cout<< "Plus assignment operator called! \n"; Cpmv temp; temp.pi->qcode = pi->qcode + obj.pi->qcode; temp.pi->zcode = pi->zcode + obj.pi->zcode; return temp; } voidCpmv::Display()const {