1. 程式人生 > >c++中的型別轉換以及explicit關鍵字

c++中的型別轉換以及explicit關鍵字

寫在前面

在沒有深入接觸c++之前,只是簡單的知道變數存在自動轉換和強制轉換,比如,int a = 3.3;

同樣也可以對類物件進行自動型別轉換以及強制型別轉換

型別轉換

使用《c++ primer plus》中的例子:

/*
Stonewt.h檔案
*/
#ifndef STONEWT_H_
#define STONEWT_H_

namespace STONE
{
	class Stonewt
	{
	private:
		enum { Lbs_to_stn = 14};
		int stone;
		double pds_left;
		double pounds;
	public:
		Stonewt(double lbs);
		Stonewt(int stn, double lbs = 0);
		Stonewt();
		~Stonewt();
		void show_lbs() const;
		void show_stn() const;
	};
}
#endif
/*
Stonewt.cpp檔案
*/
#include <iostream>
#include "Stonewt.h"
using std::cout;

namespace STONE
{
	Stonewt::Stonewt(double lbs)
	{
		stone = (int)lbs / Lbs_to_stn;
		pds_left = (int)lbs % Lbs_to_stn + lbs - (int)lbs;
		pounds = lbs;
	}
	Stonewt::Stonewt(int stn, double lbs)
	{
		stone = stn;
		pds_left = lbs;
		pounds = stn * Lbs_to_stn + lbs;
	}
	Stonewt::Stonewt()
	{
		stone = pounds = pds_left = 0;
	}

	Stonewt::~Stonewt()
	{
	}

	void Stonewt::show_stn()const
	{
		cout << stone << " stone, " << pds_left << "pounds\n";
	}
	void Stonewt::show_lbs()const
	{
		cout << pounds << " pounds\n";
	}
}

在c++中,接受一個引數的建構函式可以將型別與該引數相同的值轉換為類:Stonewt (double lbs)

可以這樣:

Stonewt mycat;
mycat = 19.6;

程式使用建構函式建立一個臨時Stonewt物件,並使用19.6對他進行初始化,隨後將內容複製到mycat中,不需要進行強制型別轉換

只接受一個引數的建構函式可以用來型別轉換,接受兩個引數建構函式,當第二個引數有預設值時也可以用來進行型別轉換,如:

Stonewt(int stn, double lbs = 0);

當要關閉這種隱式轉換,可以使用explicit關鍵字,但是如果增加explicit關鍵字,顯示轉換還是可以進行的

Stonewt mycat;
mycat = (Stonewt) 19.6;
mycat = Stonewt(19.6);

 測試程式:(未新增explicit)

#include <iostream>
#include "Stonewt.h"
using std::cout;
using STONE::Stonewt;
void display(const Stonewt &st, int n);

int main()
{
	Stonewt mycat;
	Stonewt wolft(158.5);

	mycat = 19.6;
	mycat.show_stn();

	display(wolft, 1);
	display(275, 1);
	system("pause");
}

void display(const Stonewt &st, int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << "Wow! ";
		st.show_stn();
	}
}

當新增explicit關鍵字後,會出現下面錯誤

轉換函式

數字可以轉換為Stonewt物件,那麼Stibewt物件也可以轉換為數字,要實現這種方法,必須提供對應的轉換函式

operator typename() //typename為要轉換成的型別

注意:轉換函式必須為類方法,轉換函式不能指定返回型別,轉化函式不能有引數

那麼,要轉換為double型別的函式原型為:operator double()

operator double() const;    //Stonewt.h檔案中加入
Stonewt::operator double() const   //Stonewt.cpp檔案中加入
{
	return pounds;
}

//測試程式
Stonewt wolft(158.5);
double num = wolft;
cout << "num: " << num << "\n";

可以看到Stonewt物件已經轉換成了double型別

參考書籍

《c++ primer plus 第六版》