1.注意对于类型运算符的重载,如:
#include <iostream>
using namespace std;
class MyInt
{
int nVal;
public:
MyInt( int n) { nVal = n ;}
// 在此处补充你的代码
};
int Inc(int n) {
return n + 1;
}
int main () {
int n;
while(cin >>n) {
MyInt objInt(n);
objInt-2-1-3;
cout << Inc(objInt);
cout <<",";
objInt-2-1;
cout << Inc(objInt) << endl;
}
return 0;
}
上面的Inc函数的形参为整型,故需要重载Int运算符:
operator int() {
return nVal;
}
2.二维数组的重载方法:
#include <iostream>
#include <cstring>
using namespace std;
class Array2 {
int x,y;
int **pa;
public:
Array2(int i=0,int j=0){ //构造函数
x=i;
y=j;
pa = new int*[x];
for(int u = 0; u < x; u++)
pa[u] = new int[j];
}
int * operator [] (int i){ //重载[]
return pa[i];
}
int & operator () (int i,int j){ //重载()
return pa[i][j];
}
Array2 & operator = (const Array2 & a){ //重载 = ,深拷贝
if (pa==a.pa) return *this;
x=a.x;y=a.y;
if (a.pa==NULL) {
if (pa) delete []pa;
pa=NULL;
x=0;y=0;
return *this;
}
if(x*y<a.x*a.y) {
if (pa) delete []pa;
pa = new int*[x];
for(int i = 0; i < x; i++){
pa[i] = new int[y];
}
}
memcpy (pa,a.pa,sizeof(int)*a.x*a.y);
return *this;
}
};
int main() {
Array2 a(3,4);
int i,j;
for( i = 0;i < 3; ++i )
for( j = 0; j < 4; j ++ )
a[i][j] = i * 4 + j;
for( i = 0;i < 3; ++i ) {
for( j = 0; j < 4; j ++ ) {
cout << a(i,j) << ",";
}
cout << endl;
}
cout << "next" << endl;
Array2 b; b = a;
for( i = 0;i < 3; ++i ) {
for( j = 0; j < 4; j ++ ) {
cout << b[i][j] << ",";
}
cout << endl;
}
return 0;
}
//样例输出
//0,1,2,3,
//4,5,6,7,
//8,9,10,11,
//next
//0,1,2,3,
//4,5,6,7,
//8,9,10,11,
注意点1:重载二维数组的思路,a[i][j]即pa[i].[j]的形式,且重载的[ ]函数的类型为int *
注意点2:无需重载流输出cout << ,因为二维数组返回的就是int型(?)
3.
char 与 int 之间相互转化:
int main(){
//int类型转换为char类型
int num = 6;
char c = num + '0';
cout<<c<<endl;
//char类型转换为int类型
char c1 = '4';
int num1 = c1 - '0';
cout<<num1<<endl;
}