C++ 复数运算符重载

标签 c++ operator-overloading operator-keyword

我正在尝试重载 >> 和 << 运算符以用于复数类。出于某种原因,我的 << 和 >> 函数无法访问复杂对象的实部和虚部,即使我已将它们设为类的 friend 。

复杂.h:

#ifndef COMPLEX_H
#define COMPLEX_H

class Complex
{

friend std::ostream &operator<<(std::ostream &out, const Complex &c);
friend std::istream &operator>>(std::istream &, Complex &);

public:
     explicit Complex(double = 0.0, double = 0.0); // constructor
     Complex operator+(const Complex &) const;
     Complex operator-(const Complex &) const;

#endif

复杂.cpp:

#include "stdafx.h"
#include "Complex.h"
#include <iostream>
using namespace std;

istream &operator>>(istream &input, Complex &complex) // input
{
     cout << "enter real part:\n";
     input >> complex.real;
     cout << "enter imag part: \n";
     input >> complex.imaginary;
     return input;
}

std::ostream &operator<<(std::ostream &out, Complex c)     //output
{
     out<<"real part: "<<c.real<<"\n";
     out<<"imag part: "<<c.imag<<"\n";
     return out;
}

最佳答案

没有与您定义的相同函数成为 friend 。您与第一个成为 friend ,并定义了第二个:

friend std::ostream &operator<<(std::ostream &out, const Complex &c);
       std::ostream &operator<<(std::ostream &out,       Complex  c)

还有,成员是imaginary还是imag

 input >> complex.imaginary;
 out<<"imag part: "<<c.imag<<"\n";

关于C++ 复数运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24834651/

相关文章:

c++ - 如何重载 I/O 运算符 C++

c++ - 在解决编译器错误 C2678 时遇到问题

c++ - 如何在类里面重用和重新初始化 c++ discrete_distribution?

c++ - C++ 程序员的特定 actionscript 函数

c++ - 尝试在 macOS Mojave 上捕获 OpenCV 视频时出现 "Abort Trap: 6"

c++ - 如何重载运算符 [][]

c++ - 如何在 Win x64 上使用 WinAPI 正确安装虚拟打印机?

c++ - 继承类中对运算符 << 的 undefined reference

python - Python 中 bool 值 'and' 和 'or' 的运算符方法是什么?

c++ - 左移位运算符重载