(目录)
一、java的自动包装机制
java中的基本数据类型,比如int,对应有包装类Integer。基本数据类型int与包装类Integer之间可以借助自动包装机制实现双向的自由转换。
package cerana.com;
public class Test {
public static void main(String[] args) {
Integer i = 10;
int j = i + 10;
if (i == 10)
System.out.println("i=" + i + ", " + "j=" + j);
}
}
输出:
i=10, j=20
二、C++实现“自动包装机制”
c++中的类通过单参的构造函数可以通过隐式转换将基本数据类型(比如int),转换为类类型。同时,c++的转换函数(类成员函数)也可以通过隐式转换将类类型转换为基本数据类型(比如int)。
#include <iostream>
using namespace std;
class Integer {
private:
int value;
public:
Integer() {
}
// 构造函数
Integer(int value_) { // int -> 类对象
value = value_;
}
~Integer() {
}
// 转换函数
operator int() { // 类对象 -> int
return value;
}
};
int main(int argc, const char **argv) {
Integer i = 10;
int j = i + 10;
if (i) // 对象i隐式转换为10 —— if(cin) 可用的原因
cout << "i=" << i << ", " << "j=" << j << endl;
return 0;
}
输出:
i=10, j=20
三、前置++与后置++
#include <iostream>
using namespace std;
class Integer {
private:
int value;
public:
Integer() {
}
Integer(int value_) {
value = value_;
}
~Integer() {
}
operator int() {
return value;
}
Integer& operator ++() { // ++i,返回左值
value += 1;
return *this;
}
Integer operator ++(int) { // i++,返回右值
Integer old = *this;
value += 1;
return old;
}
};
int main(int argc, const char **argv) {
Integer i1 = 10, i2 = 20;
int j1 = i1++;
int j2 = ++i2;
cout << "j1=" << j1 << ", i1=" << i1 << endl;
cout << "j2=" << j2 << ", i2=" << i2 << endl;
Integer i3 = 10;
Integer &j3 = ++i3; // 左值引用
Integer &&j4 = i3++; // 右值引用
cout << "i3=" << i3 << ", j3=" << j3 << ", j4=" << j4 << endl;
return 0;
}
输出:
j1=10, i1=11
j2=21, i2=21
i3=12, j3=12, j4=11
从上边前置++和后置++的实现来看,显然前置++(++i)的效率要高。