C++学习笔记 lesson4 构造函数2

#include<iostream>
 
class ClassDemo
{
public:
	ClassDemo() 
	{
		std::cout << "ClassDemo()...被调用" << _num << std::endl;
	};
	ClassDemo(int num):_num(num)
	{
		std::cout << "ClassDemo("<< _num<<")...被调用" << std::endl;
	};
	~ClassDemo() 
	{
		std::cout << "~ClassDemo()...被调用" << _num << std::endl;
	};
	ClassDemo & operator=(const ClassDemo&other)
	{
		std::cout << " operator=(const ClassDemo&)...被调用" << _num << std::endl;
		_num = other._num;
		return *this;
	}
	ClassDemo(const ClassDemo&other)//拷贝构造函数 参数为引用
	{
		std::cout << "ClassDemo(ClassDemo&)...被调用" << _num << std::endl;
		_num = other._num;
		
	}
	//ClassDemo(const ClassDemo other) 无限递归,编译无法通过
	//将形参
	int GetNum() const
	{
		return _num;
	};
private:
	int _num;
};

void F1(ClassDemo demo) //调用拷贝构造函数产生的临时对象
{
	demo.GetNum(); //,使用的是临时对象
	//销毁了临时对象 
}
void F2(const ClassDemo&demo)  
{
	demo.GetNum(); //只能调用const方法
}


int main()
{
	ClassDemo demo = 10;
	//调用默认构造
	demo = 20; 
	//==>demo.operator=(ClassDemo(20)) 打印出的_num是调用方的_num
	//调用默认构造temp
	//调用默认operator=(const ClassDemo&other)
    //调用析构
	ClassDemo demo1 = demo;
	//ClassDemo(ClassDemo&)被调用
	
	ClassDemo   demo1(10);
	// ClassDemo(10)...被调用
	F1(demo1);   //产生了新的临时对象
	// ClassDemo(&)...被调用
	//~ClassDemo()...被调用10
	F2(demo1); //没有新的对象产生

	return 0;
	//~ClassDemo()...被调用10
} 
 //空类中的方法
class ClassDemo
{

  //默认无参构造
	// ClassDemo(){}
  //默认析构
	// ~ClassDemo(){}
  //默认拷贝构造
	// ClassDemo(const ClassDemo& other){}
  //默认赋值
	// ClassDemo& operatot=(const CLassDemo other){}

//如果有属性
private:
	int _num;
	//默认拷贝构造
	// ClassDemo(const ClassDemo& other){num=other._num}
	//默认赋值
	// ClassDemo& operatot=(const CLassDemo other){num=other._num}

};

class MyString
{
public:
	MyString()
	{
		_len = 100;
		_str = new char[_len];
	}
	MyString(const char*str) :_len(strlen(str))
	{
		_str = new char[_len + sizeof(char)];
		strcpy(_str, str);
	}
	~MyString()
	{
		if (_str)
			delete[]_str;
	}

	MyString(const MyString & other)
	{
		delete[]_str;
		_len = other._len;
		_str = new char[_len + sizeof(char)];
		strcpy(_str, other._str); //深拷贝 在对象中,维护了所有参数的生命周期,所有参数的生命周期和我的对象同步

	  //_str = other._str; //浅拷贝:直接对指针赋值 的行为,存在风险,指针的赋值被delete
		//_len = other._len; //没有维护参数的生命周期,给别人来维护了
	}
	char *GetString()
	{
		return _str;
	}

private:
	char *_str; //有指针的情况
	int _len;
};

void test()
{
	MyString  str("I love Mark");
	MyString sb = str;//拷贝构造
	std::cout << sb.GetString() << std::endl;
	sb = "I Need Mark!!";
    // 产生临时对象,
	//对sb进行赋值 operator(MyString&)(sb._str=temp._str;_len=temp.len)
	//析构临时对象temp delete temp._str ==》等同于  delete sb._str(指向同一块区域,已经被释放了,野指针)
	std::cout << sb.GetString() << std::endl;
	
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值