gpt4 book ai didi

C++ istream 运算符重载 - 即使声明为 friend 也无法访问数据成员

转载 作者:行者123 更新时间:2023-11-27 23:02:10 25 4
gpt4 key购买 nike

我有一个 Complex 类,我正在尝试重载 istream 运算符 >> 以允许用户以“(a, b)”的形式输入复数。下面是我的头文件和我的实现。现在,我收到一条错误消息,指出我的重载 >> 函数无法访问实数或虚数数据成员,因为它们不可访问,即使我在类头文件中将它们声明为友元。谁能解释我没有看到的东西?

头文件:

// Complex class definition.
#ifndef COMPLEX_H
#define COMPLEX_H

class Complex
{
friend std::ostream &operator<<(std::ostream &, const Complex &);
friend std::istream &operator>>(std::istream &, const Complex &);
public:
explicit Complex( double = 0.0, double = 0.0 ); // constructor
Complex operator+( const Complex & ) const; // addition
Complex operator-( const Complex & ) const; // subtraction
//Complex operator*(const Complex &); // function not implemented yet
private:
double real; // real part
double imaginary; // imaginary part
}; // end class Complex

#endif

执行文件:

// Complex class member-function definitions.
#include <iostream>
#include <iomanip>
#include "Complex.h" // Complex class definition
using namespace std;

// Constructor
Complex::Complex( double realPart, double imaginaryPart )
: real( realPart ),
imaginary( imaginaryPart )
{
// empty body
} // end Complex constructor

// addition operator
Complex Complex::operator+( const Complex &operand2 ) const
{
return Complex( real + operand2.real,
imaginary + operand2.imaginary );
} // end function operator+

// subtraction operator
Complex Complex::operator-( const Complex &operand2 ) const
{
return Complex( real - operand2.real,
imaginary - operand2.imaginary );
} // end function operator-

// display a Complex object in the form: (a, b)
ostream &operator<<(ostream &out, const Complex &operand2)
{
out << "(" << operand2.real << ", " << operand2.imaginary << ")";

return out; // enable cascading output
}

// change the imaginary and real parts
istream &operator>>(istream &in, Complex &operand2)
{
in.ignore(); // skips '('
in >> setw(1) >> operand2.real; // get real part of the number
in.ignore(2); //ignore the , and space
in >> setw(1) >> operand2.imaginary;
in.ignore(); // skip ')'
return in; // enable cascading input
}

最佳答案

你的错误在这里

 friend std::istream &operator>>(std::istream &, const Complex &);
// ^^^^^

这与您定义的(正确的)签名不匹配

 istream &operator>>(istream &in, Complex &operand2)

关于C++ istream 运算符重载 - 即使声明为 friend 也无法访问数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com