C++ 类型转换运算符

一、整体代码

       Interger.h

#ifndef _INTEGER_H_
#define _INTEGER_H_
class Integer
{
public:
    Integer(int n);
    ~Integer();
    Integer& operator++();
    //friend Integer& operator++(Integer& i);
    Integer operator++(int n);
    //friend Integer operator++(Integer& i, int n);
    operator int();
    void Display() const;
private:
    int n_;
};
#endif // _INTEGER_H_

      Interger.cpp

#include "Integer.h"
#include <iostream>
using namespace std;
Integer::Integer(int n) : n_(n)
{
}
Integer::~Integer()
{
}
Integer& Integer::operator ++()
{
    //cout<<"Integer& Integer::operator ++()"<<endl;
    ++n_;
    return *this;
}
//Integer& operator++(Integer& i)
//{
//    //cout<<"Integer& operator++(Integer& i)"<<endl;
//    ++i.n_;
//    return i;
//}
Integer Integer::operator++(int n)
{
    //cout<<"Integer& Integer::operator ++()"<<endl;
    //n_++;
    Integer tmp(n_);
    n_++;
    return tmp;
}
//Integer operator++(Integer& i, int n)
//{
//    Integer tmp(i.n_);
//    i.n_++;
//    return tmp;
//}
Integer::operator int() //重载了类型转换运算符,返回int型
{
    return n_;
}
void Integer::Display() const
{
    cout<<n_<<endl;
}

      01.cpp

#include "Integer.h"
#include <iostream>
using namespace std;
int add(int a, int b)
{
    return a + b;
}
int main(void)
{
    Integer n(100);
    n = 200;
    n.Display(); //200
    int sum = add(n, 100);
    cout<<sum<<endl;//300
    int x = n;//n.operator int()
    int y = static_cast<int>(n);
    return 0;
}


你可能感兴趣的:(C++ 类型转换运算符)