C++基础知识整理九(const和类 this指针)

本文主要介绍了C++中const关键字在类中的应用,包括const成员函数的定义与作用,以及如何创建const对象。同时,还探讨了this指针的使用,特别是在成员函数中this->x的含义及其指向成员变量的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,const和类

Classstudent.cpp代码如下:

#include "pch.h"
#include <iostream>
#include "Cstudent.h"
using namespace std;

int main(int argc, char* argv[])
{
	Cstudent stu((char*)"li", (char*)"a001", 80);
	stu.print();
	return 0;
}

Cstudent.cpp代码如下:

#include "pch.h"
#include "Cstudent.h"
#include <iostream>
using namespace std;

Cstudent::Cstudent(char* myName, char* myNum, float myScore):matchScore(myScore)
{
	strcpy_s(name, myName);
	strcpy_s(stuNum, myNum);
}

Cstudent::Cstudent(char* myName, char* myNum):matchScore(0)
{
	strcpy_s(name, myName);
	strcpy_s(stuNum, myNum);
}


Cstudent::~Cstudent(void)
{
}

void Cstudent::setName(char* myName)
{
	strcpy_s(name , myName);
}

void Cstudent::setNum(char* myNum)
{
	 strcpy_s(stuNum , myNum);
}


void Cstudent::print()
{
	cout << "姓名" << name << ",学号" << stuNum << ",数学成绩:" << matchScore << endl;
}

Cstudent.h代码如下: 

#pragma once
class Cstudent
{
public:
	Cstudent(char* myName,char* myNum, float myScore);//构造函数
	Cstudent(char* myName, char* myNum);
	~Cstudent(void);//析构函数
private:
	char name[10];
	char stuNum[10];
	const float matchScore;
public:

	void setName(char* myName);
	void setNum(char* myNum);
	void print();
};

 Classstudent.cpp代码不变

Cstudent.cpp代码更改如下:

void Cstudent::print()const//const成员函数
{
    cout << "姓名" << name << ",学号" << stuNum << ",数学成绩:" << matchScore << endl;
}

Cstudent.h代码更改如下: 

void print()const;//const成员函数

3, const对象

 Classstudent.cpp代码更改如下:

const Cstudent stu((char*)"li", (char*)"a001", 80);

4,this指针

其中this->x指的是int x,y;中的x; this->x = x中的=右边的 “x”指的是setPoint里面的形参int x

pointTest.cpp代码如下:

#include "pch.h"
#include <iostream>
#include "CMyPoint.h"
using namespace std;

int main(int argc ,char* argv[])
{
	CMyPoint pt(2, 3);
	CMyPoint pt1(0, 0);
	pt1.copy(pt);
	cout << pt1.x << "," << pt1.y << endl;//由于这部分的x y是私有类型,所以不可能通过对象直接访问它,需要将 .h文件里面的private改为public
	return 0; 
	
}

 CMypoint.cpp代码如下

#include "pch.h"
#include "CMyPoint.h"

CMyPoint::CMyPoint(int x,int y)
{
	this->x = x;
	this->y = y;
}

CMyPoint::~CMyPoint()
{
}

void CMyPoint::copy(CMyPoint pt)
{
	*this = pt;
	
}

 CMypoint.h代码如下

#pragma once
class CMyPoint
{
public:
	CMyPoint(int x,int y);
	~CMyPoint();
public:
	int x, y;
public:
	void copy(CMyPoint pt);//成员函数
};

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值