代码之家  ›  专栏  ›  技术社区  ›  For

如何使用c++中的=运算符分别分配复变量的实部和虚部?

  •  0
  • For  · 技术社区  · 1 年前

    我正在尝试使用 complex<> 类型来实现点类,用于几何图形问题。

    我希望能够通过 = 操作数。

    像这样:

    class Point
    {
    public:
        complex<int> my_point;
    
        int& real(); // This should assign `my_point.real()` using `=`.
        int& imag(); // Same for `my_point.imag()`.
    }
    
    Point p;        // p is {0, 0}
    p.real() = 10;  // p is {10, 0}
    p.imag() = 20;  // p is {10, 20}
    

    如果能够使用相同的语法检索这些值,将非常有帮助。

    cout << p.imag(); // p is {10, 20}, so this should print `20`.
    

    我该怎么做?

    2 回复  |  直到 1 年前
        1
  •  -1
  •   doug    1 年前

    使用 The exception that allows constexpr as shown here 以及调整Shreyash的想法:

    对于std::complex类型的任何对象z,reinterpret_cast<T(&)[2]>(z) [0]是z的实部,并且interpret_ cast<T(&)[2]>(z) [1]是z的虚部

    只需将T替换为 int 如果只需要一个int复杂类型,就可以删除模板。

    #include <complex>
    #include <iostream>
    
    template <class T>  // floating point type
    class Point
    {
    public:
        std::complex<T> my_point;
    
        T& real()
        {
            return reinterpret_cast<T(&)[2]>(my_point)[0];
        }
    
        T& imag()
        {
            return reinterpret_cast<T(&)[2]>(my_point)[1];
        }
    
        T real() const
        {
            return my_point.real();
        }
    
        T imag() const
        {
            return my_point.imag();
        }
    };
    
    int main()
    {
        Point<int> p;
        p.real() = 10;
        p.imag() = 20;
    
        std::cout << p.imag() << std::endl;
        return 0;
    }
    
        2
  •  -2
  •   Shreeyash Shrestha    1 年前

    我想这回答了你的问题:

    class Point
    {
    public:
        std::complex<int> my_point;
    
        int& real()
        {
            return my_point.real();
        }
    
        int& imag()
        {
            return my_point.imag();
        }
    
        int real() const
        {
            return my_point.real();
        }
    
        int imag() const
        {
            return my_point.imag();
        }
    };
    

    然后使用您想要的方法来分配或获得实点和虚点的值。可能是这样的:

    int main()
    {
        Point p;
        p.real() = 10;
        p.imag() = 20;
    
        std::cout << p.imag() << std::endl;
    
        return 0;
    }
    

    试一下,让我知道它是否有效

    编辑 由于上一次尝试不起作用,我想你需要进行强制转换。我尝试使用重新解释强制转换,它对我有效。以下是我尝试的代码:

    //same code as previous
        int& real()
        {
            return reinterpret_cast<int*>(&my_point)[0];
        }
    
        int& imag()
        {
            return reinterpret_cast<int*>(&my_point)[1];
        }
    
        int real() const
        {
            return reinterpret_cast<const int*>(&my_point)[0];
        }
    
        int imag() const
        {
            return reinterpret_cast<const int*>(&my_point)[1];
        }
    //remaining same code here as well 
    

    让我知道它对你有效与否,因为它对我有效