C++ 类型转换运算符
2013-11-06 12:49
190 查看
一、整体代码
Interger.h
Interger.cpp
01.cpp
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++中四种类型转换运算符
- C++中四种类型转换运算符详解
- C++ 类型转换运算符
- 《C++ Primer Plus》15.5 类型转换运算符 学习笔记
- C++中类型转换运算符的使用方法
- C++中的数据类型转换运算符
- 从零开始学C++之从C到C++(二):引用、内联函数inline、四种类型转换运算符
- C++ 类型转换运算符——const_cast
- C++中四种类型转换运算符的使用方法
- C++中四种类型转换运算符的使用方法
- c++ 重载类型转换运算符
- c++的类型转换和运算符
- C++中四种类型转换运算符的使用方法
- C++中四种类型转换运算符的使用方法
- c++新增的4个类型转换运算符
- 走进C++程序世界----类型转换运算符
- 从零开始学C++之运算符重载(四):类型转换运算符、*运算符重载、->运算符重载、operator new 和 operator delete .
- C++中四种类型转换运算符的使用方法
- C++ 四种类型转换运算符详解
- C++ 学习笔记(4)表达式、运算符、类型转换(static_cast、const_cast、reinterpret_cast、dynamic_cast)