C++之友元函数、const和static、类的组合

友元函数:friend修饰函数

友元函数提供一个对象具有打破权限的功能

eg1:

class Test{
public:
	void print()
	{
		cout << this->name << "\t" << this->age << endl;
	}
	friend void printData(Test&);//定义友元函数
protected:
	string name = "xiaoming";
private:
	int age = 18;
};

void printData(Test &test)
{
	cout << "友元函数调用" << endl;
	cout << test.name << "\t" << test.age << endl;
}

eg2:
一个类的成员函数是另一个类的友元函数

//要先把B2类先放到前面
class B2 {
public:
	void printB();
};
class A2 {
public:
	//声明友元函数
	friend void B2::printB();

protected:
	void printA()
	{
		cout << "A" << endl;
	}
private:
	void printAA()
	{
		cout << "AA" << endl;
	}
};

void B2::printB()
{
	A2 a;
	a.printA();
	a.printAA();
}

B2 b2;
b2.printB();

友元类

const 成员

  1. 常数据成员: const修饰的数据成员
    const属性代表只读(不可以修改)
    常数据成员的初始化必须要采用初始化参数列表
    形式如下:

    class MyTest {
    public:
    MyTest(string name, int id) :name(name), id(id) {} //这里用初始化列表来init
    protected:
    string name;
    const int id; //常数据成员
    };

2.常成员函数:const修饰的成员函数不可以修改类的成员
在常成员函数中不可以修改数据成员
常成员函数和普通函数可以同时存在

class MyTest {
public:
	MyTest(string name, int id) :name(name), id(id) {}

	//普通函数和常成员函数同时存在并且名字相等
	void print()
	{
		cout << "普通函数被调用" << endl;
		cout << this->name << "\t" << this->id << endl;
	}
	void print() const
	{
		cout << "const成员函数被调用" << endl;
		cout << this->name << "\t" << this->id << endl;
		//this->name = "www"; 在const修饰的成员函数中不能修改类的成员
	}
protected:
	string name;
	const int id;    //常数据成员
};

int main()
{
	//普通对象可以调用普通函数或常成员函数
	MyTest myTest("xiaoming", 20);
	myTest.print();

	//常对象:只能调用常成员函数
	const MyTest test("laowang", 40);
	test.print();

	system("pause");
	return 0;
}

3**.常对象**: const修饰的对象,不能访问普通函数 只能访问常成员函数

static

  1. .static静态数据成员
    必须在类外初始化
    静态数据成员是属于类的,不属于对象,是所有对象公有,也就是说所有对象用的是 一个数据
    静态数据成员访问不需要对象,可以直接用类名限定访问: 类名::成员
    静态数据成员也受权限限定
class StaticTest {
public:
	StaticTest(string name, int count) :name(name)
	{
		StaticTest::count = count;
	}
protected:
	string name;
	static int count;  //静态数据成员
};

//static静态数据成员需要在类外初始化
int StaticTest::count = 0;
  1. static静态成员函数
    访问可以不需要对象,用对象访问也可以的
    也受权限限定
    静态成员不能直接访问非静态数据成员,只能通过指定

类的组合

一个类作为另一个类的成员
如下:

class Mother {
public:
	Mother() {	cout << "Mother无参构造函数被调用" << endl;}
	Mother(string name, int age) :name(name), age(age) {}
protected:
	string name;
	int age;
};
class Father {
public:
	Father() { cout << "Father无参构造函数被调用" << endl; }
	Father(string name, int age) :name(name), age(age) {}
protected:
	string name;
	int age;
};

class Family {
public:
	//组合类的构造函数如何写?
	Family() {}  //类的组合必须存在无参的构造函数
	Family() :father("xiaoming", 10), mother("zhangsan", 20) {}
protected:
	Mother mother;
	Father father;
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值