class A {
public:
A(int a=0)
:_aa(a)
{
cout <<_aa << endl;
}
private:
int _aa;
};
class B {
private:
int _a;
int* p = nullptr;
int* pp = (int*)malloc(4);
};
int main() {
B bb;
A c1(1);
A c2 = 2;//单参数构造函数支持隐式类型转换
//所以是2构造一个临时对象然后拷贝构造
const A& c3 = 4;
return 0;
}
缺省值可以是其他的变量不局限于常量
如果不想存在隐式类型转换的话可以加explicit在构造函数前面: c2和c3就出错了
多参数类型:
class A {
public:
A(int a=0,int b=1)
:_aa(a)
,_bb(b)
{
cout <<_aa <<" ";
cout << _bb << endl;
}
private:
int _aa;
int _bb;
};
class B {
private:
int _a;
int* p = nullptr;
int* pp = (int*)malloc(4);
};
int main() {
B bb;
A c1(1,2);
A c2 = {3,4};
const A& c3 = {5,6};
return 0;
}
class Date
{
//友元函数
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1)
:_year(year)
,_month(month)
,_day(day)
{}
private:
int _year;
int _month;
int _day;
};
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "/" << d._month << "/" << d._day << endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
in >> d._year >> d._month >> d._day;
return in;
}
int main()
{
Date d1;
cin >> d1;
cout << d1;
return 0;
}
友元函数是普通的全局函数:
#include <iostream>
using namespace std;
class A
{
private:
int A;
public:
print(){};
//声明全局函数 person 是 类A 的友元函数
friend void person (int &x);
}
void person(int &x)
{
//使用了类A的成员变量age
cout << "age=" << p.age << endl;
}
int main ()
{
A p(22);
person(p);
return 0;
}
友元函数是其他类的成员函数:
#include <iostream>
using namespace std;
class A
{
private:
int A;
public:
print(){};
//声明类B的成员函数 person 是 类A 的友元函数
friend void B::person (int &x);
}
class B
{
private:
int B;
public:
person(int &x);
}
B::person(int &x)
{
//因为类B的成员函数person是类A的友元函数,所以看可以使用类A的成员变量age
cout << "age=" << p.age << endl;
}
int main ()
{
A p(22);
B q;
q.person(p);
return 0;
}
注意:
友元函数可访问类的私有和保护成员,但不是类的成员函数
友元函数不能用const修饰
友元函数可以在类定义的任何地方声明,不受类访问限定符限制
一个函数可以是多个类的友元函数
友元函数的调用与普通函数的调用原理相同
3.2 友元类
友元类的所有成员函数都可以是另一个类的友元函数,都可以访问另一个类中的非公有成员。
友元关系是单向的,不具有交换性。
比如上述Time类和Date类,在Time类中声明Date类为其友元类,那么可以在Date类中直接
访问Time类的私有成员变量,但想在Time类中访问Date类中私有的成员变量则不行。
友元关系不能传递:如果C是B的友元, B是A的友元,则不能说明C时A的友元。
友元关系不能继承(后续解析)
//时间类
class Time
{
friend class Date;
// 声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成员变量
public:
//成员函数的初始化列表
Time(int hour = 0, int minute = 0, int second = 0)
: _hour(hour)
, _minute(minute)
, _second(second)
{}
private:
int _hour;
int _minute;
int _second;
};
//日期类
class Date
{
public:
//成员函数的初始化列表
Date(int year = 1900, int month = 1, int day = 1)
: _year(year)
, _month(month)
, _day(day)
{}
void SetTimeOfDate(int hour, int minute, int second)
{
// 直接访问时间类私有的成员变量,因为日期类是时间类的友元类
_t._hour = hour;
_t._minute = minute;
_t._second = second;
}
private:
int _year;
int _month;
int _day;
Time _t;
};
// 1、B类受A类域和访问限定符的限制,其实他们是两个独立的类
// 2、内部类默认就是外部类的友元类
class A
{//外部类不能访问内部类
public:
class B // B天生就是A的友元
{
public:
void print(const A& a)
{
cout << k << endl; //可以直接访问A的静态成员变量
cout << a.h << endl; //也可以访问A的成员变量
}
};
private:
static int k;
int h;
};
int A::k = 1;