”^“运算符重载实现幂指数运算

来源:互联网 发布:淘宝品牌调性分怎么查 编辑:程序博客网 时间:2024/04/30 11:24
/*重载运算符“^”实现数组各对应元素相乘方。如:a[3]={ 2,2,2 } ,b[3]={ 3,3,3 } ,则a^b={ 8,8,8 } 。具体要求如下:(1)私有数据成员:    int a[3];(2)公有成员函数:    构造函数:初始化数据成员;    重载运算符“^”的友元函数;    void print():输出数组成员的函数;(3)在主函数中定义对象t1(以数组a作参数)、t2(以数组b作参数)和t3(无参),通过语句“t3=t1^t2;” 对类进行测试。*/#include<iostream>#include<cmath>using namespace std;class CF{private:    int a[3];public:    CF(int []);    friend CF & operator ^ (CF &, CF &);    void print();};CF::CF(int temp[]){    for (int i = 0; i < 3; i++)    {        a[i] = temp[i];    }}CF & operator ^(CF & cf1, CF& cf2){    for (int i = 0; i < 3; i++)    {        cf1.a[i] = pow(cf1.a[i], cf2.a[i]);    }    return cf1;}void CF::print(){    for (int i = 0; i < 3; i++)    {        cout << a[i] << '\t';    }    cout << endl;}int main(){    int a[] = { 2,2,2 }, b[] = { 2,3,4 };    CF cf1(a), cf2(b);    CF cf3 = cf1^cf2;    cf3.print();    system("pause");    return 0;}
原创粉丝点击