c++学习笔记 四

const

初始化const成员变量使用初始化列表

class AA
{
private:
	int const m_a; 
	int m_b;
public:
	AA():m_a(100) //类中只能用初始化列表初始const变量
	{
	
	}
	void show ()const;
};
#include<iostream>
using namespace std;

class AA
{
private:
	int const m_a; 
	int m_b;
public:
	AA():m_a(100) //类中只能用初始化列表初始const变量
	{
	
	}
	void show ()const;
};
void AA::show (/*const AA * const this*/)const // 常函数不能修改成员变量
{
	m_b=20;
}
	int main()
{
	const AA a;
	a.show();//	 常对象只能使用常函数
	system("pause");
return 0;
}

函数前加const标识返回值类型为const 函数后加表示为常函数        

class和struct

struct在c++中可以有成员函数

struct AA
{
	int a;
	AA()
	{
	a=100;
	}
	~AA()
	{
	
	};


};

string 

#include<iostream>
using namespace std;



int main()
{
	char *str=new char[10];
	strcpy_s(str,10,"abcde");
	str[1]='B';
   
        
	system("pause");
return 0;
}

 类之间的关系

1 、组合

        

#include<iostream>
using namespace std;

class Head
{
public:
void say()
{

cout<<"说话"<<endl;
}
};
class Hand
{
public:
void move()
{

cout<< "比划"<<endl;
}
};
class person
{
private:
	Head m_head;
	Hand m_hand;
public:
	void meeting()
	{
	cout<<"开会了"<<endl;
	this->m_head.say();
	this->m_hand.move();
	}
};

int main()
{
	
	person per;
	per.meeting();
	system("pause");
return 0;
}

 2 依赖

 

#include<iostream>
using namespace std;

class computer
{
public:
	void code()
	{
		cout<<"#include<iostream>...."<<endl;
	}

};

class person
{

public:
	void coding(computer &cp)
	{
	cout<<"打代码"<<endl;
	cp.code();
	}
};

int main()
{
	computer cp;
	person per;
	per.coding(cp);
	system("pause");
return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值