C++this关键字&Static&Const&友元函数&友元

11 篇文章 0 订阅
8 篇文章 1 订阅
this
class Clock{
	private:
		int hour,minute,second;
	public:
		void setClock(int h,int m,int s);
}; 
void Clock::setClock(Clock *this,int h,int m,int s){
	this->hour=h;
	this->minute=m;
	this->second=s;
}
Static

1,Static数据成员

static用来修饰类的成员,控制成员的存储方式。静态数据成员是该类所有对象共有的。静态数据成员只分配一次内存,供所有对象共用。


静态数据初始化格式:数据类型  类名::静态数据成员 = 值

int X::s = 0;

访问静态数据成员的方式:

类对象名.静态数据成员名

类类型名::静态数据成员名

//计算一组学生的总成绩和平均值
#include<iostream>
#include<cstring>
using namespace std;
class Student{
	private:
		char name[20];
		int age;
		float score;
	public:
		Student(char *n,int a,int s){
			strcpy(name,n);
			age = a;
			score =s;
			sum += score;
		}
		static float sum;
};
//对静态数据成员进行 初始化
float Student::sum = 0; 
int main(){
	Student stud[3] = {Student("zhang san",20,60),Student("Li si",19,70),Student("wang wu",18,78)};
	float average;

	
	average =Student::sum/3;
	cout<<"sum="<<Student::sum<<"average="<<average<<endl;
	return 0; 
}

2,Static函数成员


Const

const用来定义常量,就是值不变的量,const定义常量必须在构造函数的初始化列表中进行初始化。

常成员函数:

#include<iostream>
using namespace std;
class Circle{
	private:
		double x,y;
		double radius;
		const double pi;//
	public:
		//构造函数 
		Circle(double x,double y,double radius,double pi):pi(pi){
			this->x =x;
			this->y = y;
			this->radius = radius;
		}
		double getRadius(){
			return radius;
		} 
		//常成员函数 
		double area() const{
			return pi*radius*radius; 
		}
};
int main(){
	Circle c1(1.2,3.4,3,3.14);
	cout<<c1.area();
	return 0;
}

常成员函数既可以访问常数据成员也可以访问非常数据成员。

常对象

const Circle c1(1.2,3.4,3,3.14);

友元函数

普通函数作为类的友元函数













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凤凰AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值