设计一个计算类,包含两个数据成员,他们类型相同,可能同时是int,char,double,Complex,Mylnteger.提供有求和,求差的计算
时间: 2024-03-16 09:45:22 浏览: 81
好的,根据您的要求,我设计了如下的计算类:
```c++
#include <iostream>
using namespace std;
class Calculator{
private:
int m_iValue1;
int m_iValue2;
char m_cValue1;
char m_cValue2;
double m_dValue1;
double m_dValue2;
Complex m_complexValue1;
Complex m_complexValue2;
Mylnteger m_myint1;
Mylnteger m_myint2;
public:
Calculator(int v1, int v2) : m_iValue1(v1), m_iValue2(v2) {}
Calculator(char v1, char v2) : m_cValue1(v1), m_cValue2(v2) {}
Calculator(double v1, double v2) : m_dValue1(v1), m_dValue2(v2) {}
Calculator(Complex c1, Complex c2) : m_complexValue1(c1), m_complexValue2(c2) {}
Calculator(Mylnteger m1, Mylnteger m2) : m_myint1(m1), m_myint2(m2) {}
template <typename T>
T add(T v1, T v2){
return v1 + v2;
}
template <typename T>
T sub(T v1, T v2){
return v1 - v2;
}
};
//定义Complex和Mylnteger类
class Complex{
public:
Complex(double r=0, double i=0) : real(r), imag(i) {}
Complex operator+(Complex &c){
return Complex(real+c.real, imag+c.imag);
}
Complex operator-(Complex &c){
return Complex(real-c.real, imag-c.imag);
}
private:
double real;
double imag;
};
class Mylnteger{
public:
Mylnteger(int n=0) : num(n) {}
Mylnteger operator+(Mylnteger &m){
return Mylnteger(num+m.num);
}
Mylnteger operator-(Mylnteger &m){
return Mylnteger(num-m.num);
}
private:
int num;
};
int main(){
//测试
Calculator cal1(3, 5);
cout << "3+5=" << cal1.add(cal1, cal1) << endl;
cout << "3-5=" << cal1.sub(cal1, cal1) << endl;
Calculator cal2('a', 'b');
cout << "a+b=" << cal2.add(cal2, cal2) << endl;
cout << "a-b=" << cal2.sub(cal2, cal2) << endl;
Calculator cal3(3.14, 2.718);
cout << "3.14+2.718=" << cal3.add(cal3, cal3) << endl;
cout << "3.14-2.718=" << cal3.sub(cal3, cal3) << endl;
Complex c1(1, 2);
Complex c2(3, 4);
Calculator cal4(c1, c2);
Complex res = cal4.add(c1, c2);
cout << "1+2i + 3+4i = " << res.real << "+" << res.imag << "i" << endl;
res = cal4.sub(c1, c2);
cout << "1+2i - 3+4i = " << res.real << "+" << res.imag << "i" << endl;
Mylnteger m1(10);
Mylnteger m2(5);
Calculator cal5(m1, m2);
cout << "10+5=" << cal5.add(m1, m2).getNum() << endl;
cout << "10-5=" << cal5.sub(m1, m2).getNum() << endl;
return 0;
}
```
这里定义了一个`Calculator`类,包含了五种不同类型的数据成员,同时提供了`add`和`sub`两个模板函数,用于实现两个数据成员的求和和求差操作。其中,`add`和`sub`函数都是模板函数,可以接受任意类型的数据成员作为输入。为了支持复数和自定义整数类型的计算,我们还需要定义`Complex`和`Mylnteger`两个类,它们都重载了加法和减法运算符。
在主函数中,我们分别创建了不同类型的`Calculator`对象,并调用了`add`和`sub`函数进行测试。您可以根据需要修改数据成员的类型,并测试不同类型的数据计算。
阅读全文