#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;
}
C++学习笔记 lesson4 构造函数2
最新推荐文章于 2017-02-06 23:28:05 发布