C++入门知识(一)——类的引入、访问控制、this指针、重载、指针和引用

一、类的引入、类与对象

C++中结构体与类的区别

class Person_kind2 {
	char *name;
	int age;
	char *work;
};
int main(int argc,char**argv)
{
	int i;						//int是类型,i是变量
	Person_kind2 lisi;	//Person_kind2是类,lisi是对象
}

二、访问控制

C++中对于结构体、类内的数据有三种访问权限设置:1、private 2、protected 3、public

public:可以被任意实体访问

protected:只允许子类及本类的成员函数访问

private:只允许本类的成员函数访问

三、this指针

this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员
如下例:

#include <iostream>
using namespace std;

class Student{
public:
    void setname(char *name);
    void setage(int age);
    void setscore(float score);
    void show();
private:
    char *name;
    int age;
    float score;
};
void Student::setname(char *name){
    this->name = name;
}
void Student::setage(int age){
    this->age = age;
}
void Student::setscore(float score){
    this->score = score;
}
void Student::show(){
    cout<<this->name<<"的年龄是"<<this->age<<",成绩是"<<this->score<<endl;
}
int main(){
    Student *pstu = new Student;
    pstu -> setname("李华");
    pstu -> setage(16);
    pstu -> setscore(96.5);
    pstu -> show();
    return 0;
}

四、重载

实现同名函数,当函数名相同,参数不同时即为重载。
参数不同的几种情况:
1、参数类型不同
2、参数数量不同
3、参数顺序不同

返回值类型不同无法作为重载条件

#include <iostream>
using namespace std;
int show(int a,int b)
{
	cout<<"a="<<a<<"b="<<b<<endl;
}
int show(int a,char* b)
{
	cout<<"a="<<a<<"b="<<b<<endl;
}
int show(int a,int b,int c)
{
	cout<<"a="<<a<<"b="<<b<<"c="<<c<<endl;
}
int main(int argc,char**argv)
{
	show(10,20);
	show(10,"拉");
	show(10,20,30);
	return 0;
}

在这里插入图片描述
当实现两个返回值不同的函数时:

#include <iostream>
using namespace std;
int show(int a,int b)
{
	cout<<"a="<<a<<"b="<<b<<endl;
	return 0;
}
char* show(int a,int b)
{
	cout<<"a="<<a<<"b="<<b<<endl;
	return "ok";
}
int main(int argc,char**argv)
{
	show(10,20);
	return 0;
}

在这里插入图片描述

五、指针和引用

引用就是别名,定义引用时必须初始化(也就是说要设定是谁的别名)。

int a = 1;int &b = a;//b既是a的别名,以后用到b即是a
int 张三;int &小三 = 张三;//小三是张三的别名,以后叫小三就是叫张三

具体例子如下

#include <iostream>
using namespace std;

int add_one(int a)
{
	a = a + 1;
	return a;
	
}
int add_one(int *a)
{
	*a = *a + 1;
	return *a;
}
int add_one_ref(int &a)
{
	a = a + 1;
	return a;
}

int main(int argc,char**argv)
{
	int a = 10;
	int &c = a;
	cout<<"start_c = "<<c<<endl;
	cout<<"start_a = "<<a<<endl;
	cout<<"add_one = "<<add_one(a)<<endl;
	cout<<"add_one = "<<add_one(&a)<<endl;
	cout<<"add_one = "<<add_one_ref(a)<<endl;
	cout<<"end_a = "<<a<<endl;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值