如何在 C++ 中使用 = 操作数分别分配复数变量的实部和虚部?

问题描述 投票:0回答:1

我正在尝试使用

complex<>
类型来实现 Point 类,以解决几何问题。

我希望能够通过

=
操作数单独分配变量的实部和虚部的值。

像这样:

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`.

我该怎么做?

c++ geometry variable-assignment complex-numbers assignment-operator
1个回答
0
投票

我想这回答了你的问题:

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;
}

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

© www.soinside.com 2019 - 2024. All rights reserved.