三巨头(复制构造函数,赋值运算符=,析构函数) [英] The Big Three (Copy Constructor, Assignment Operator =, Destructor)

查看:135
本文介绍了三巨头(复制构造函数,赋值运算符=,析构函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题,从课程的最后一期考试..

我知道当我们管理资源时,我们必须编写复制构造函数,赋值运算符和析构函数..所以,是这样的叫做三巨头的法则.. !!



现在请关注我的代码..

输出不正确。相反,它给了我地址,而不是正确的价值..



请帮帮我..



well this is question, from final term exam of the course ..
I know when we manage the resource, we have to write copy constructor, assignment operator and destructor .. So, is so called the law of Big Three .. !!

Now Please have an eye on my code ..
The output is not correct.. instead it is giving me the address, not the proper value ..

Please Help Me Out ..

#include <iostream>
using namespace::std;

class myClass{
	float *fptr;
public:
	myClass(){
		fptr = NULL;
	}
	myClass(float val){
		fptr = new float;
		*fptr = val;
	}
	float get(){
		return *fptr;
	}
	void set(float value){
		*fptr = value;
	}
	void print(){
		cout << "f p t r  = " << this->fptr << "\n\n";
	}
	myClass(const myClass &yourClass){ // copy constructor
		fptr = new float;
		fptr = yourClass.fptr;
	}
	myClass& operator=(const myClass & yourClass){ // Assignment Operator
		if (this != &yourClass)
		{
			delete fptr;
			fptr = new float;
			fptr = yourClass.fptr;
		}
		return *this;
	}
	~myClass(){ // destructor
		delete fptr;
	}
};

int main(){
	myClass me(3);
	me.print();
	myClass you(me);
	you.print();
	return 0;
}

推荐答案

你需要取消引用指针。



1.在print()中用* fptr替换this-> fptr。



2.用* fptr = * yourclass替换fptr = yourClass.fptr复制构造函数和赋值运算符中的.fptr。



3.赋值运算符有错误。在删除fptr之前检查NULL。析构函数同上。
You need to de-reference the pointer.

1. replace this->fptr with *fptr in print().

2. replace fptr = yourClass.fptr with *fptr = *yourclass.fptr in copy constructor and assignment operator.

3. assignment operator has a bug. Check for NULL before deleting fptr. Ditto for destructor.


这篇关于三巨头(复制构造函数,赋值运算符=,析构函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆