#include<iostream>
usingnamespace std;
class MYCLASS
{
public:
MYCLASS()=default;
/*explicit*/ MYCLASS(string str): strValue(str)
{
cout <<"----MYCLASS(string str)"<< endl;
}
MYCLASS(int iValue): intValue(iValue)
{
cout <<"----MYCLASS(int iValue)"<< endl;
}
/**< 拷贝构造函数 */
MYCLASS(const MYCLASS & myClass)
{
cout <<"----MYCLASS(const MYCLASS& myClass)"<< endl;
strValue = myClass.strValue;
}
/**< 拷贝赋值运算符 */
MYCLASS &operator=(const MYCLASS & myClass)
{
cout <<"----MYCLASS& operator=(const MYCLASS& myClass)"<< endl;
this->intValue = myClass.intValue;
this->strValue = myClass.strValue;
return*this;
}
string getStrValue()
{
return strValue;
}
int getIntValue()
{
return intValue;
}
void setIntValue(int iValue)
{
intValue = iValue;
}
void setStrValue(string str)
{
strValue = str;
}
private:
string strValue;
int intValue;
};
int main()
{
/**< 当类的构造函数只有一个参数且该构造函数没有被explicit修饰时,可以直接用该参数类型的变量来给类对象赋值 */
MYCLASS myClass1 = string("2014-11-25");
/**
* 首先调用MYCLASS(string str)生成一个临时的MYCLASS变量
* 然后调用MYCLASS(const MYCLASS & myClass)将该临时变量赋值给myClass1
* 由于编译器存在优化机制,所以这里会直接调用MYCLASS(string str)来初始化myClass1
*/
//MYCLASS myClass2 = 100;
MYCLASS myClass2 = myClass1;/**< 调用拷贝构造函数 */
myClass2.setIntValue(100);
myClass1 = myClass2;/**< 调用的是拷贝赋值运算符 */
/**< 初始化类对象使用=时调用拷贝构造函数,当类对象创建完成之后使用=进行赋值时调用的是拷贝赋值运算符 */
cout << myClass2.getStrValue()<<"--"<< myClass2.getIntValue()<< endl;
return0;
}
/**
* 输出结果:
* ----MYCLASS(string str)
* ----MYCLASS(const MYCLASS& myClass)
* ----MYCLASS& operator=(const MYCLASS& myClass)
* 2014-11-25--100
*/