友元函数
让函数成为类的友元,让该函数具有和类成员函数相同的访问权限。
friend void func(argument) 在类声明中添加友元函数原型。
- 虽然友元函数是在类中声明的,但它不是成员函数,不能使用成员运算符来调用。
- 友元函数虽然不是成员函数,但是它与成员函数具有相同的访问全限。
- 函数定义不需要类名加作用域解析运算符,也不需要friend关键字。
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
class Complex{
private:
float real;
float imag;
public:
Complex(float real=0, float imag = 0);
Complex operator +(Complex & other) const; // const成员函数表示不会修改对象内容
void show() const;
friend ostream & operator << (ostream &os, const Complex&t);
friend Complex operator +(float real, Complex & other); // 友元
};
ostream & operator<<(ostream&os, const Complex&t)
{
os<<t.real<<" + "<<t.imag<<"j"<<endl;
return os;
}
Complex operator + (float real, Complex & other) // 不用friend 和类名加作用域解析运算符
{
Complex ans;
ans.real = real + other.real;
ans.imag = other.imag;
return ans;
}
Complex::Complex(float real, float imag)
{
this->real = real;
this->imag = imag;
}
Complex Complex::operator+(Complex & other) const
{
Complex comp;
comp.real = this->real + other.real;
comp.imag = this->imag + other.imag;
return comp;
}
void Complex::show() const
{
cout<<this->real<<" + "<<this->imag<<"j"<<endl;
}
int main()
{
Complex a = Complex(1,2);
Complex c = 3+a;
cout<<c;
return 0;
}
类的自动转换和强制类型转换
- 当类有一个只有一个构造参数的构造函数时,编译器可以将某类型数据隐式转换为类类型的数据。
- 转换函数,可以将类对象转换为其他类型。转换函数时类成员没用返回类型,没用参数。名为operator typeName()。
- 禁用上述隐式转换,要使用关键字explicit
#include<iostream>
using namespace std;
class A{
public:
int x;
A(int x);
operator int(){return x;}; // 转换函数可以把类对象转换为int
};
A::A(int x)
{
this->x = x;
}
class B{
public:
double x;
explicit B(double x){this->x = x;};
explicit operator double(){return x;};
};
int main()
{
A a = 10;
int ax = a; // 隐式类型转换,int和A类对象互转
// 因为使用了explicit所以需要显示的进行类型转换。
B b = (B)3.14;
double bx = (double)b;
cout<<int(a.x == ax)<<endl;
cout<<int(b.x == bx)<<endl;
return 0;
}

浙公网安备 33010602011771号