c++ - 返回对 C++11 中复数的实数或虚数值的引用的函数

标签 c++ gcc c++11 complex-numbers

我正在寻找一个函数,该函数返回对 C++11 中复数的实数或虚数值的引用。在 C++03 中我可以说:

complex<double> C; cin >> C.real();

但在 C++11 中,由于 C.real() 返回的值不是引用,因此会出现编译错误。

我发现我可以这样写:

double t; cin >> t; C.real(t);

但这并不简单,例如,如果我想将 c 的实数部分乘以 2 并将其乘以 1,我应该说:

C.real(2*C.real() + 1);

那不干净。

还有其他[干净]的方法吗?

最佳答案

如果您真的想将复数的实部和虚部的输入分开,您可以尝试 IO 操纵器方法。

#include <complex>
#include <iosfwd>

class proxy_complex {
    explicit proxy_complex(std::istream& strm, bool f)
        : strm_(&strm), flag(f) { }
    proxy_complex(const proxy_complex&) = default;

    std::istream* strm_;
    bool flag;           // flag to check whether we're writing real or imag

public:
    template<typename T>
    std::istream& operator>>(std::complex<T>& c)
    {
        T n;
        if (*strm_ >> n)
            flag ? c.real(n) : c.imag(n);
        return *strm_;
    }

    friend proxy_complex operator>>(std::istream& is, proxy_complex(*func)(std::istream&))
    {
        return func(is);
    }
    friend proxy_complex real(std::istream&);
    friend proxy_complex imag(std::istream&);
};

inline proxy_complex real(std::istream& is)
{
    return proxy_complex(is, true);
}

inline proxy_complex imag(std::istream& is)
{
    return proxy_complex(is, false);
}

您可以将上述代码放在它自己的头文件中(如果这样做,最好将其包装在命名空间中)。

用法:

#include <iostream>
#include "my_header.h"

int main()
{
    std::complex<double> c;
    std::cin >> real >> c >> imag >> c;
    if (std::cin) std::cout << c;
}

希望我猜对了你对“干净”的定义:)

关于c++ - 返回对 C++11 中复数的实数或虚数值的引用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175776/

相关文章:

c++ - c++0x 元组是否使用新的可变参数模板或 Boost 的宏元组实现?

c++ - 外部、链接和全局变量

c - 使用 RPATH 但不使用 RUNPATH?

C 字符数组始终为空。内核开发

linux - 标准库 ABI 兼容性

c++ - 从 native 句柄创建 std::thread?

c++ - if语句问题?

c++ - 按顺序打印二叉搜索树

c++ - 析构函数的模板特化

C++:监视器和条件变量进程间