有兩種方法:(1)采用重載雙目運算符方式
(2)1.類型轉換函數(將類的對象轉換為其他數據類型)
2.轉換構造函數(將其他類型轉換為類的對象)(仍然要配合重載雙目運算符的方式,因為最終實現的是類的兩個對象相加)
(注意:類型轉換函數和轉換構造函數不可同時使用,會出現二義性!)
/*以下程序均以‘+’為例!*/
一:采用重載運算符方式(需要考慮重載符號的左右值順序,左值為本類對象,則重載函數不需要兩個參數;若左值為其他類型,則需要聲明為友元函數,
同時函數參數個數需要2個,並在類外定義普通的函數。詳細如下程序。)
(1)對象+數據 (采用重載運算符方式)
#include <iostream>
using namespace std;
//依據對象數據類型
//假設對象數據是整型,則傳進來的double型與對象的數據相加再轉為整型
class test
{
public:
test() {}
test(int a1) :a(a1) {}
test operator +(double r) //當主函數‘+’的左邊是對象時,只寫一個傳進來的參數
{
a = a + r;
return test(a);
}
void show()
{
cout << a << endl;
}
private:
int a;
};
int main()
{
test t1(1);
test t2;
t2 = t1 + 2.3;
t2.show();
system("pause");
return 0;
}
(2)數據+對象 (采用重載運算符方式)
#include <iostream>
using namespace std;
//依據對象數據類型
//假設對象數據是整型,則傳進來的double型與對象的數據相加再轉為整型
class test
{
public:
test() {}
test(int a1) :a(a1) {}
friend test operator +(double r, test&t); //當主函數‘+’的左邊不是對象而是數據時,需定義友元函數,並且參數個數一定要有2個
void show()
{
cout << a << endl;
}
private:
int a;
};
test operator+( double r,test&t) //注意普通函數的寫法
{
return (t.a + r);
}
int main()
{
test t1(1);
test t2;
t2 = 2.3 + t1;
t2.show();
system("pause");
return 0;
}
二:采用類型轉換函數(符號左右值不需要考慮順序)
(數據+對象||對象+數據)
#include <iostream>
using namespace std;
class test
{
public:
test(){}
test(int a1):a(a1){}
operator double() //類型轉換函數,將一個類的對象轉換成其他數據類型如:類test t->double;
{
return a;
}
void show()
{
cout<<a<<endl;
}
private:
int a;
};
int main()
{
test t1(1);
test t;
t=1.2 + t1; //如無其他轉換構造函數,則調用類型轉換函數,將t1轉換為double類型,t最終也會轉換為double類型
t.show();
system("pause");
return 0;
}
三:采用轉換構造函數(配合重載雙目運算符函數)
#include <iostream>
using namespace std;
class test
{
public:
test(){}
test(double r):a(r){} //定義轉換構造函數
test operator +(test &t)
{
a=a+t.a;
return test(a);
}
void show()
{
cout<<a<<endl;
}
private:
double a;
};
int main()
{
test t1(1);
test t=1.2; //調用轉換構造函數,將1.2轉換為一個類的對象
test t3=t1 + t;
t3.show();
system("pause");
return 0;
}