2014-12-19 28 views
-1

我一直在閱讀有關運算符重載,我不明白什麼是轉換運算符以及它如何有用。有人可以請解釋一個例子嗎?什麼是轉換運算符在c + +中使用

+0

你的意思是用於提供一種類型和另一種之間的轉換路徑的方法? – tadman 2014-12-19 04:43:55

+0

http://en.cppreference.com/w/cpp/language/cast_operator – 2014-12-19 04:44:36

回答

0

轉換操作符可幫助程序員將一個具體類型轉換爲另一個具體類型或原語類型的含義。這裏是從http://www.geeksforgeeks.org/advanced-c-conversion-operators/

示例截取的示例:

#include <iostream> 
#include <cmath> 

using namespace std; 

class Complex 
{ 
private: 
    double real; 
    double imag; 

public: 
    // Default constructor 
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) 
    {} 

    // magnitude : usual function style 
    double mag() 
    { 
     return getMag(); 
    } 

    // magnitude : conversion operator 
    operator double() 
    { 
     return getMag(); 
    } 

private: 
    // class helper to get magnitude 
    double getMag() 
    { 
     return sqrt(real * real + imag * imag); 
    } 
}; 

int main() 
{ 
    // a Complex object 
    Complex com(3.0, 4.0); 

    // print magnitude 
    cout << com.mag() << endl; 
    // same can be done like this 
    cout << com << endl; 
}