Complex class [PrintMax]

Complex class [PrintMax]

本文关键字:PrintMax class Complex      更新时间:2023-10-16

所以我正在研究"TEMPLATES",我需要对一个名为PrintMax的函数进行3次尝试——这是显而易见的——打印一个由3个元素组成的数组中的最大元素,每次尝试都针对这个数组中的不同数据类型——double/int/complex——。因此,我需要首先创建Complex类及其所需的运算符重载,然后使用PrintMax函数作为模板函数来处理3种类型的数组。

这里的问题在于第三个数组,当然,我不能将Complex的元素写入(a+bi(的数组中,因为这是我的类Complex:

    class Complex
{
private :
    int imaginary;
    int real;
public:
    Complex (int = 0, int = 0);
    ~Complex ();
    int getImaginary();
    int getReal();
    void setImagniary(int i);
    void setReal (int r);
    bool operator > (Complex&);
};

你可以注意到,我超载了operator>来检查,但我也有一个小问题,除了不能用那种方式写元素之外,第二个问题是我不能——或者昏昏欲睡,我的大脑正在死亡——计算这个复数数组中的最大值:

// Input: Complex Array
// 1+3i, 2+4i, 3+3i
// Expected Output: 2+4i

所以我想把它们分配到数组中,形式是:Arr[3]={1+3i,2+4i,3+3i};

为什么这是预期产出,为什么不是3+3i?

感谢阅读~

在我看来,你正在寻找这样的东西:

template <typename T> void PrintMax(T array[])
{
   // It is assumed that array has 3 elements in it.
   std::cout <<
      array[0] > array[1] ?
        (array[0] > array[2] ? array[0] : array[2]) :
        (array[1] > array[2] ? array[1] : array[2])
        std::endl;
}

您可以使用以下内容。请注意,代码中没有范围检查,这只是为了演示如何解决问题。

另外,我建议您使用容器(例如std::vector(而不是纯数组。

#include <algorithm>
#include <cmath>
#include <iostream>
class Complex {
private:
    int imaginary;
    int real;
public:    
    Complex(int r, int i) :
            imaginary(i), real(r) {
    }
    ~Complex() {
    }
    int getImaginary() const {
        return imaginary;
    }
    int getReal() const {
        return real;
    }
    void setImaginary(int i) {
        imaginary = i;
    }
    void setReal(int r) {
        real = r;
    }
    double getAbsolut() const {
        return std::abs(std::sqrt(std::pow(imaginary, 2) + std::pow(real, 2)));
    }
    friend bool operator<(const Complex& lhs, const Complex& rhs);
    friend std::ostream& operator<<(std::ostream& stream,
            const Complex& complex);
};
bool operator<(const Complex& lhs, const Complex& rhs) {
    return lhs.getAbsolut() < rhs.getAbsolut();
}
std::ostream& operator<<(std::ostream& stream, const Complex& complex) {
    stream << "Complex(" << complex.real << "+" << complex.imaginary
            << "i)";
    return stream;
}
template<int size, class T>
void getMax(const T arr[]) {
    T max_value = arr[0];
    for (size_t i = 1; i < size; ++i) {
        max_value = std::max(max_value, arr[i]);
    }
    std::cout << "max: " << max_value << std::endl;
}
int main(int argc, char **argv) {
    Complex arr_complex[] = { Complex(3, 3), Complex(2, 4), Complex(1, 3) };
    int arr_int[] = { 3, 5, 1 };
    double arr_double[] = { 2.3, 5.6, 9.1 };
    getMax<3>(arr_complex);
    getMax<3>(arr_int);
    getMax<3>(arr_double);
    return 0;
}