c++ - 在c++中实现复数幂函数?

标签 c++ class operator-overloading

就像标题所说,我正在尝试实现一个运算符 ^(int n) ,它将计算一个复数的 n 次方。我知道 this 是一个指向当前类对象的指针,所以我想出了以下代码:

    class Complex{
    protected:
      float a,b;
    public:
      Complex() {a=0;b=0;}
      Complex(float x, float y){a=x;b=y;}
      void set(float x, float y){a=x;b=y;}
      Complex operator*(Complex C){
                Complex temp;
                temp.a=a*C.a-b*C.b;
                temp.b=a*C.b+b*C.a;
                return temp;
      }
      Complex operator^(int n){
                Complex ONE=Complex(1,0);
                if (n<=0) return ONE;
                return ((*this)*((*this)^(n-1)));
      }
      void Display(){
                cout<<a<<' '<<b<<endl;
      }
      };
      int main() {
          Complex C;
          C.set(2,0);
          C=C^3;
          C.Display();
      }

C.Display() 应该打印 8 0 但当我在 eclipse 中运行时它显示 2 0。请告诉我为什么会发生这种情况。如果有人能告诉我如何在第 15 行使 ONE 成为常量类对象,如 Java 中的 BigInteger.ONE,我也非常感激。

最佳答案

你知道有一个 std::complex模板类型,有自己的std::pow特化?

#include <complex>
#include <iostream>

int main() {

  std::complex<double> c(2,0);
  std::complex<double> c3 = pow(c, 3);
  std::cout << c3 << "\n";
}

产生

(8,0)

此外,operator^ 是按位异或。重复使用它作为幂运算符将导致非常困惑的代码。

除此之外,您的代码会产生您期望的结果,因此问题一定出在其他地方。

关于c++ - 在c++中实现复数幂函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10688134/

相关文章:

c++ - boost asio检测/避免接收缓冲区溢出

Ruby:如何使类中只有一个方法公开?

c++ - 未找到重载函数

c++ - 在 C++ 中共享相同名称的类和命名空间

C#语法糖重载

c++ - 具有运算符重载的 accumulate()

c++ - 返回一个结构而不初始化它

c++ - 在没有手动分配缓冲区的情况下使用 sprintf

C++使用源码、静态存档等动态库创建动态库

html - 在 css 中悬停 - 文本会破坏悬停?