1. 程式人生 > >C++ 轉換函式舉例

C++ 轉換函式舉例

#include<iostream>
#include<vector>

using namespace std;

class A
{
   public:
    A(int a, int b) : a(a), b(b) {}
    inline int operator <<(int c) { return a + c;}
    inline operator std::vector<int>&() {return _buf;}

    inline operator double()
    {
        return ((double)a/(double)b);
    }
    inline operator int*()
    {
        return &b;
    }

    private:
        int a;
        int b;
        std::vector<int> _buf;
};

int main()
{
    A x(10, 4);
    int c = x<<(1);
    double xx = 4 + x;

    float x1 = *x;
    std::cout << c  << std::endl;  
    std::cout << xx << std::endl;
    std::cout << x1 << std::endl;
    return 0;
}