Write a simple function template for predict function isEqualTo that compares its two arguments of the same type with the equality operator (==) and returns true if they are equal and false if they are not equal. Use this function template in a program that calls isEqualTo only with a variety of built-in types. Now write a separate version of the program that calls isEqualTo with a user-defined class type Complex, but does not overload the equality operator. What happens when you attempt to run this program? Now overload the equality operator (with the operator function) operator ==. Now what happens when you attempt to run this program?
时间: 2023-11-22 21:54:36 浏览: 120
Here is the function template for isEqualTo:
```
template<typename T>
bool isEqualTo(const T& a, const T& b) {
return a == b;
}
```
Here is an example program that uses isEqualTo with built-in types:
```
#include <iostream>
int main() {
std::cout << std::boolalpha;
std::cout << isEqualTo(5, 5) << std::endl;
std::cout << isEqualTo(5, 7) << std::endl;
std::cout << isEqualTo('a', 'a') << std::endl;
std::cout << isEqualTo('a', 'b') << std::endl;
std::cout << isEqualTo(true, true) << std::endl;
std::cout << isEqualTo(true, false) << std::endl;
std::cout << isEqualTo(3.14, 3.14) << std::endl;
std::cout << isEqualTo(3.14, 2.71) << std::endl;
return 0;
}
```
When we attempt to run this program with the user-defined class type Complex, we get a compilation error because the compiler doesn't know how to compare two Complex objects.
To fix this, we can overload the equality operator in the Complex class:
```
class Complex {
public:
Complex(double real, double imag) : m_real(real), m_imag(imag) {}
double real() const { return m_real; }
double imag() const { return m_imag; }
private:
double m_real;
double m_imag;
};
bool operator==(const Complex& lhs, const Complex& rhs) {
return lhs.real() == rhs.real() && lhs.imag() == rhs.imag();
}
```
Now when we attempt to run the program with Complex objects, it works as expected:
```
#include <iostream>
class Complex {
public:
Complex(double real, double imag) : m_real(real), m_imag(imag) {}
double real() const { return m_real; }
double imag() const { return m_imag; }
private:
double m_real;
double m_imag;
};
bool operator==(const Complex& lhs, const Complex& rhs) {
return lhs.real() == rhs.real() && lhs.imag() == rhs.imag();
}
template<typename T>
bool isEqualTo(const T& a, const T& b) {
return a == b;
}
int main() {
std::cout << std::boolalpha;
std::cout << isEqualTo(Complex(1.0, 2.0), Complex(1.0, 2.0)) << std::endl;
std::cout << isEqualTo(Complex(1.0, 2.0), Complex(3.0, 4.0)) << std::endl;
return 0;
}
```
Output:
```
true
false
```
阅读全文
相关推荐


















