c++构造函数重载乘法运算
时间: 2023-10-18 09:14:46 浏览: 73
假设我们有一个名为`Complex`的类,表示复数。该类有两个私有成员变量`real`和`imaginary`,分别表示实部和虚部。我们可以重载乘法运算符来使`Complex`类支持复数乘法。以下是一个示例:
```c++
#include <iostream>
class Complex {
public:
Complex() : real(0), imaginary(0) {}
Complex(double r, double i) : real(r), imaginary(i) {}
Complex operator*(const Complex& other) const {
double newReal = real * other.real - imaginary * other.imaginary;
double newImaginary = real * other.imaginary + imaginary * other.real;
return Complex(newReal, newImaginary);
}
void print() const {
std::cout << "(" << real << ", " << imaginary << "i)" << std::endl;
}
private:
double real;
double imaginary;
};
int main() {
Complex a(1, 2);
Complex b(3, 4);
Complex c = a * b;
c.print(); // 输出:(-5, 10i)
return 0;
}
```
在上面的代码中,我们定义了一个名为`operator*`的函数,该函数重载了乘法运算符。它接受一个`Complex`类型的参数`other`,并返回一个新的`Complex`对象,该对象的实部和虚部分别是两个复数的乘积。在`main`函数中,我们创建了两个复数`a`和`b`,然后将它们相乘,得到一个新的复数`c`。最后,我们调用`c.print()`函数来输出结果。