运算符重载(使用二元友元函数)class没有成员,且成员不可访问
operator overloading(using binaray friend function) class has no member, and member inaccessible
在做有关运算符重载的 youtube 教程时,我无法修复运算符重载(使用友元函数)错误消息。收到的消息是关于 class Complex 没有成员 "operator+" 和 class
"Complex::real" 在第 7 行声明的是不可访问的。
// link 我正在努力学习的教程
https://www.youtube.com/watch?v=AlCYu_mc-T8
// 错误信息从这里开始://
#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
int real, imag;
public:
void read();
void show();
friend Complex operator+ (Complex , Complex); // Friend function declaration
};
void Complex::read()
{
cout << "Enter real value: ";
cin >> real;
cout << "Enter imaginary value: ";
cin >> imag;
}
void Complex::show()
{
cout << real;
if (imag < 0)
cout << "-i";
else
cout << "+i";
cout << abs(imag) << endl;
}
Complex Complex::operator+(Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
int main()
{
Complex c1, c2, c3;
c1.read();
c2.read();
c3 = c1 + c2; // invokes operator + (Complex, Complex)
cout << "Addition of c1 and c2 = ";
c3.show();
return 0;
}
friend
不是会员。因此,更改此行:
Complex Complex::operator+(Complex c1, Complex c2)
至:
Complex operator + (Complex c1, Complex c2)
在做有关运算符重载的 youtube 教程时,我无法修复运算符重载(使用友元函数)错误消息。收到的消息是关于 class Complex 没有成员 "operator+" 和 class "Complex::real" 在第 7 行声明的是不可访问的。
// link 我正在努力学习的教程 https://www.youtube.com/watch?v=AlCYu_mc-T8
// 错误信息从这里开始://
#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
int real, imag;
public:
void read();
void show();
friend Complex operator+ (Complex , Complex); // Friend function declaration
};
void Complex::read()
{
cout << "Enter real value: ";
cin >> real;
cout << "Enter imaginary value: ";
cin >> imag;
}
void Complex::show()
{
cout << real;
if (imag < 0)
cout << "-i";
else
cout << "+i";
cout << abs(imag) << endl;
}
Complex Complex::operator+(Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
int main()
{
Complex c1, c2, c3;
c1.read();
c2.read();
c3 = c1 + c2; // invokes operator + (Complex, Complex)
cout << "Addition of c1 and c2 = ";
c3.show();
return 0;
}
friend
不是会员。因此,更改此行:
Complex Complex::operator+(Complex c1, Complex c2)
至:
Complex operator + (Complex c1, Complex c2)