编写一个Sample类模板,内有2个不同类型的私有数据成员,请在该类模板中设计一个operator--重载运算符函数,用于比较各对象的数据成员是否相等。
时间: 2024-03-05 19:49:09 浏览: 23
好的,下面是代码实现:
```cpp
template<typename T1, typename T2>
class Sample {
private:
T1 data1;
T2 data2;
public:
Sample(T1 d1, T2 d2): data1(d1), data2(d2) {}
bool operator--(const Sample& s) const {
return (data1 == s.data1 && data2 == s.data2);
}
};
```
在上面的代码中,我们使用了类模板(template),定义了一个名为 Sample 的类。该类有两个私有数据成员 data1 和 data2,分别为 T1 和 T2 类型。在类模板中,我们还定义了一个构造函数,用于初始化 data1 和 data2。最后,我们重载了 operator-- 运算符函数,用于比较两个 Sample 对象的数据成员是否相等。重载函数返回一个布尔值,表示两个对象的数据成员是否相等。
相关问题
编写一个复数类模板complex,其数据成员real和image
好的,下面是一个简单的复数类模板complex的实现:
```cpp
template<typename T>
class complex {
public:
T real;
T image;
complex(T r = 0, T i = 0) : real(r), image(i) {}
complex<T> operator+(const complex<T>& other) const {
return complex<T>(real + other.real, image + other.image);
}
complex<T> operator-(const complex<T>& other) const {
return complex<T>(real - other.real, image - other.image);
}
complex<T> operator*(const complex<T>& other) const {
return complex<T>(real * other.real - image * other.image, real * other.image + image * other.real);
}
complex<T> operator/(const complex<T>& other) const {
T denominator = other.real * other.real + other.image * other.image;
return complex<T>((real * other.real + image * other.image) / denominator, (image * other.real - real * other.image) / denominator);
}
bool operator==(const complex<T>& other) const {
return (real == other.real) && (image == other.image);
}
bool operator!=(const complex<T>& other) const {
return !(*this == other);
}
friend std::ostream& operator<<(std::ostream& os, const complex<T>& c) {
os << c.real << "+" << c.image << "i";
return os;
}
};
```
这个类模板定义了一个复数类,包含实部和虚部两个数据成员。它的构造函数可以接受两个参数,分别是实部和虚部的值。同时,它还重载了加、减、乘、除、相等和不相等操作符,以及输出操作符。
设计一个数组类模板,该模板至少包含对数组元素的初始化
好的,我可以为您设计一个数组类模板。这个模板将允许您创建具有不同元素类型和大小的数组,并提供初始化功能。
下面是一个示例代码:
```cpp
template <typename T, int N>
class Array {
public:
Array() {
for (int i = 0; i < N; i++) {
data[i] = T();
}
}
Array(const T& value) {
for (int i = 0; i < N; i++) {
data[i] = value;
}
}
T& operator[](int index) {
return data[index];
}
const T& operator[](int index) const {
return data[index];
}
private:
T data[N];
};
```
这个模板类包含两个构造函数,一个是默认构造函数,另一个是带有一个参数的构造函数。默认构造函数将会初始化数组中的每个元素为类型 T 的默认值。带有参数的构造函数将会初始化数组中的每个元素为给定的值。
这个模板类还重载了 `operator[]`,以便您可以像使用普通数组一样访问数组元素。
您可以像这样使用这个模板类来创建一个具有 10 个整数元素的数组,并将它们初始化为 0:
```cpp
Array<int, 10> arr;
```
或者您可以将数组元素初始化为其他值:
```cpp
Array<int, 5> arr(42);
```
这将创建一个具有 5 个整数元素的数组,并将它们初始化为 42。