一、类的引入、类与对象
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;
}