概述
在日常的開發(fā)中, 我們經(jīng)常會用到數(shù)據(jù)類型轉(zhuǎn)換, 所以我們要對數(shù)據(jù)類型轉(zhuǎn)換有一定的了解.
不同類型數(shù)據(jù)間的轉(zhuǎn)換
在 C++ 中, 某些標(biāo)準(zhǔn)類型的數(shù)據(jù)之間可以自動轉(zhuǎn)換.
隱式類型轉(zhuǎn)換
隱式類型轉(zhuǎn)換: 由 C++ 編譯系統(tǒng)自動完成的, 我們無需干預(yù). 例如:
int main() { int a = 6; a = a + 3.5; cout << a << endl; return 0; }
輸出結(jié)果:
9
強(qiáng)制類型轉(zhuǎn)換
強(qiáng)制類型轉(zhuǎn)換: 在程序中將一種類型數(shù)據(jù)明確轉(zhuǎn)換成另一指定的類型. 例如:
int main() { int a = int(2.3); double b = double(12); cout << a << endl; cout << b << endl; return 0; }
輸出結(jié)果:
2
12
自己聲明的類型轉(zhuǎn)換
如果用我們自己聲明的類型進(jìn)行數(shù)據(jù)轉(zhuǎn)換就會發(fā)生一個問題: 編譯系統(tǒng)并不知道如何轉(zhuǎn)換.
解決辦法:
- 定義專門的函數(shù)來讓編譯系統(tǒng)知道怎樣進(jìn)行轉(zhuǎn)換
- 轉(zhuǎn)換構(gòu)造函數(shù)和類型轉(zhuǎn)換函數(shù)
轉(zhuǎn)換構(gòu)造函數(shù)
轉(zhuǎn)換構(gòu)造函數(shù) (conversion constructor function) 可以將一個其他類型的數(shù)據(jù)轉(zhuǎn)換成一個類的對象的構(gòu)造函數(shù).
例如:
#ifndef PROJECT8_COMPLEX_H #define PROJECT8_COMPLEX_H #include <iostream> using namespace std; class Complex { private: double real; double imaginary; public: Complex() {}; // 無參構(gòu)造 Complex(double r, double i) : real(r), imaginary(i) {}; // 有參構(gòu)造 Complex(Complex & c) { // 復(fù)制構(gòu)造函數(shù) cout << "copy constructor" << endl; }; Complex(double r) : real(r) {}; // 轉(zhuǎn)換構(gòu)造函數(shù) }; }; #endif //PROJECT8_COMPLEX_H
類型轉(zhuǎn)換函數(shù)
當(dāng)我們使用轉(zhuǎn)換構(gòu)造函數(shù)的時候我們可以將一個標(biāo)準(zhǔn)數(shù)據(jù)轉(zhuǎn)換為類的對象. 我們使用類型轉(zhuǎn)換函數(shù) (type conversion function) 可以將一個類的對象反過來轉(zhuǎn)換成標(biāo)準(zhǔn)類型的數(shù)據(jù).
案例
Complex 類:
#ifndef PROJECT8_COMPLEX_H #define PROJECT8_COMPLEX_H #include <iostream> using namespace std; class Complex { public: double real; double imaginary; public: Complex() {}; // 無參構(gòu)造 Complex(double r, double i) : real(r), imaginary(i) {}; // 有參構(gòu)造 Complex(double r) : real(r) {}; // 轉(zhuǎn)換構(gòu)造函數(shù) operator double() {return real;}; // 類型轉(zhuǎn)換函數(shù) Complex operator+(Complex &c) { return Complex(real + c.real, imaginary + c.imaginary); }; }; #endif //PROJECT8_COMPLEX_H
main:
#include <iostream> #include "Complex.h" using namespace std; int main() { Complex c1(3.1, 4), c2(5.2, -10); double d1, d2; d1 = c1 + 2; // 3.1 + 2, 調(diào)用類型展緩函數(shù) cout << d1 << endl; d2 = c1 + c2; // 3.1 + 5.2, 調(diào)用類型展緩函數(shù) cout << d2 << endl; return 0; }
輸出結(jié)果:
5.1
8.3
編譯系統(tǒng)會根據(jù)表達(dá)式的上下文, 自動調(diào)用類型轉(zhuǎn)換函數(shù), 將 Complex 類對象作為 double 類型數(shù)據(jù)使用.
應(yīng)用
類型轉(zhuǎn)換函數(shù)也叫做: 類型轉(zhuǎn)換運(yùn)算符函數(shù), 類型轉(zhuǎn)換運(yùn)算符重載函數(shù), 強(qiáng)制類型轉(zhuǎn)換運(yùn)算符重載函數(shù).
不同類型進(jìn)行各種混合運(yùn)算的方案:
- 轉(zhuǎn)換構(gòu)造函數(shù)
- 類型轉(zhuǎn)換函數(shù)
- 運(yùn)算符重載
進(jìn)行各種運(yùn)算時, 使用類型轉(zhuǎn)換函數(shù), 而不是對多種運(yùn)算符進(jìn)行重載. 工作量較小, 程序精干, 防止出現(xiàn)二義性.
到此這篇關(guān)于C/C++中數(shù)據(jù)類型轉(zhuǎn)換詳解及其作用介紹的文章就介紹到這了,更多相關(guān)C++數(shù)據(jù)類型轉(zhuǎn)換內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/weixin_46274168/article/details/117209139