C++ primer plus第六版课后编程题答案18.2


 

第十八章答案均由热心博友:王琪胜 提供

邮箱:wqs1639@gmail.com

如果对答案有疑问的可以发Email给我或者该博友,感谢大家一直以来的支持,

祝大家都能在编程中找到自己的最亮的那个闪光点。

————————————————————————————————————————————————————

18.2

//dev-cpp 5.6.2编译成功但是无法显示调用移动构造函数
//vs 2012里运行可以成功显示移动构造函数

#include <iostream>
#include <string>
//using namespace std;   在VS2012中若不加此声明  则必须include <string>  否则会报错
//这是因为vs2012的iostream 头文件中没有 重载operator<<(const std::string &) 重载放在了string这个头文件里所以才要加上string这个头文件
class Cpmv{
	public:
		struct Info
		{
			std::string qcode;
			std::string zcode;
		};
	private:
		Info *pi;
	public:
		Cpmv();
		Cpmv(std::string q,std::string z);
		Cpmv(const Cpmv&cp);
		Cpmv(Cpmv &&mv);
		~Cpmv();
		Cpmv& operator=(const Cpmv&cp);
		Cpmv& operator=(Cpmv &&mv);
		Cpmv operator+(const Cpmv&obj)const;
		void Display()const;
};

Cpmv::Cpmv(){
	pi=nullptr;
    std::cout<<"无参构造\n";
}

Cpmv::Cpmv(std::string q,std::string z){
	pi=new Info;
	pi->qcode=q;
	pi->zcode=z;
	std::cout<<"带参构造\n";
}

Cpmv::Cpmv(const Cpmv&cp){
	pi=new Info;
	pi->qcode=cp.pi->qcode;
	pi->zcode=cp.pi->zcode;
	std::cout<<"拷贝构造\n";
}

Cpmv::Cpmv(Cpmv&&mv){
	std::cout<<"移动构造\n";
	pi=mv.pi;
	mv.pi->qcode='\0';
	mv.pi->zcode='\0';
	mv.pi=nullptr;
}

Cpmv::~Cpmv(){
	delete pi;
	std::cout<<"析构调用\n";
}
Cpmv& Cpmv::operator=(const Cpmv&cp){
	std::cout<<"重载赋值符号\n";
	if(this==&cp)
		return *this;
	if(pi==nullptr)
		pi=new Info;
	pi->qcode=cp.pi->qcode;
	pi->zcode=cp.pi->zcode;
	return *this;
}

Cpmv& Cpmv::operator=(Cpmv&&mv){
	std::cout<<"移动赋值\n";
	if(this==&mv)
		return *this;
	delete pi;
	pi=mv.pi;
	mv.pi->qcode='\0';
	mv.pi->zcode='\0';
	return *this;
}
Cpmv Cpmv::operator+(const Cpmv&obj)const{
	Cpmv temp;
	temp.pi=new Info;
	temp.pi->qcode=pi->qcode+" "+obj.pi->qcode;
	temp.pi->zcode=pi->zcode+" "+obj.pi->zcode;
	return temp;
}
void Cpmv::Display()const{
	using std::cout;
	if(pi==nullptr)
	{
		cout<<"empty data.\n";
		return ;
	}
		
	cout<<"point pi's address :"<<&pi<<"\n";
	cout<<"qcode :"<<pi->qcode<<"\n";
	cout<<"zcode :"<<pi->zcode<<"\n";
}

int main(){
	using namespace std;
	Cpmv t1;
	t1.Display();
	Cpmv t2(string("hello"),string("world"));
	t2.Display();
	Cpmv t3(t2);
	t3.Display();
	Cpmv t4(t3);
	t4.Display();
	Cpmv t5;
	t5=t2;
	t5.Display();
	Cpmv t6=t2+t3;
	t6.Display();
	Cpmv t7(t2+t3);
	t7.Display();
	cout<<endl;
	t1.Display();
	t2.Display();
	t3.Display();
	t4.Display();
	t5.Display();
	t6.Display();
	return 0;
}

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注