c++-賦值與初始化的區別

在初始化語句中的等號(=)不是等號運算符,編譯器對這種表示方法做了特殊的解釋 

#include <iostream>

using namespace std;

class Clock
{
private:
	int hour_;
	int minute_;
	int second_;
public:
	Clock(int hour=0, int minute=0, int second=0)
	{
		hour_ = hour;
		minute_ = minute;
		second_ = second;
		cout<<"Clcok"<<endl;
	}
	~Clock()
	{
		cout<<"~Clock"<<endl;
	}
	Clock &operator=(const Clock& other)
	{
		cout<<"= operator"<<endl;
		if(this == &other)
		{
			return *this;
		}
		hour_ = other.hour_;
		minute_ = other.minute_;
		second_ = other.second_;
		return *this; 
	}
};
int main()
{
	Clock c1=30;       //初始化語句,調用的是普通的構造函數,相當於Clolck c1(30),這裏的=不是=運算符
	c1 = 20;           //調用賦值運算符,調用轉換構造函數

	return 0;
}
運行結果如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章