类和对象
#include<iostream>
using namespace std;
//面向对象的三大特征 : 封装 继承 多态
//类 是对数据和算法的封装 抽象概念
//对象 真实存在的 通过类定义出来的变量就叫对象
class Person
{
public:
//成员属性 变量
//成员方法 方法
char* name;
int age;
bool Sex;
void Eat()
{
cout << "干饭人" << endl;
}
};
int main()
{
//创建对象的方式有两种
//定义变量
//定义一个类的指针 new出来一个对象
Person ps ;
ps.name = (char*)"zhangsan";
ps.age = 17;
ps.Sex = true;
ps.Eat();
Person* p = new Person;
system("pause");
return 0;
}
访问修饰符
#include<iostream>
using namespace std;
//public 公共 类外可以访问
//private 私有 类外不能访问 只能在本类中访问
//protected 受保护 类外不能访问 在派生类中可以访问
//一个类去继承另一个类则继承的那个类为派生类
//类默认的属性为private
//成员属性设置为private 成员方法设置为public
class Student
{
private:
char* name;
int age;
float score;
public:
void Show();
//一般来说在类里面 成员方法是public 成员属性private
};
//类外实现成员函数
//返回值类型 + 类名 + :: + 函数名 + 参数列表
void Student::Show()
{
cout << name << " " << age << " " << score << endl;
}
int main()
{
Student stu;
/*stu.name =(char*)"zhangsan";
stu.age = 17;
stu.score = 92.5;*/
stu.Show();
system("pause");
return 0;
}
接口函数
#include<iostream>
using namespace std;
//接口函数 设置一些成员函数去修改获得成员变量
class Student
{
private:
char* name;
int age;
float score;
public:
void SetName(char* str);
void SetAge(int n);
void SetScore(float n);
char* GetName();
int GetAge();
float GetScore();
};
void Student::SetName(char* str)
{
name = str;
}
void Student::SetAge(int n)
{
age = n;
}
void Student::SetScore(float n)
{
score = n;
}
char* Student::GetName()
{
return name;
}
int Student::GetAge()
{
return age;
}
float Student::GetScore()
{
return score;
}
int main()
{
Student stu;
stu.SetName((char*)"zhangsan");
stu.SetAge(17);
stu.SetScore(92.5);
cout << stu.GetName() << endl;
cout << stu.GetAge() << endl;
cout << stu.GetScore() << endl;
system("pause");
return 0;
}
构造函数
#include<iostream>
using namespace std;
//构造函数没有返回值 连返回值类型都没有 名字和类名同名
//创建对象时自动调用 一定会调用 不写的话会有一个默认的来执行
//一般情况下把构造函数设置为public
//构造函数可以有多个 基于函数重载
//构造放的一般是 一个对象创建就执行的东西
class Student
{
public:
char* name;
int age;
public:
Student();
Student(char* str);
};
Student::Student()
{
name =(char*) "zhangsan";
age = 17;
}
Student::Student(char* str)
{
name = str;
age = 17;
}
int main()
{
Student stu;
cout << stu.name << endl;
cout << stu.age << endl;
Student stu1((char*)"Lisi");
cout << stu1.name << " " << stu1.age << endl;
Student* pStu = new Student ((char*)"wangwu");
cout << pStu->name << " " << pStu->age << endl;
system("pause");
return 0;
}
初始化列表
#include<iostream>
using namespace std;
class Student
{
public:
int m_age;
char* m_name;
public:
Student(char* name, int age);
};
//初始化列表
//函数实现的时候
//作用域(类名::)+ 函数名 + 参数列表 + : + 成员变量(具体的参数)
Student::Student(char* name, int age):m_name(name),m_age(age)
{
/*m_age = age;
m_name = name;*/
}
class AA
{
public:
int m_a;
int m_b;
public:
AA(int n);
};
//初始化列表的初始化顺序是与类中成员变量声明的顺序一致的
AA::AA(int n):m_a(m_b),m_b(n)
{
}
int main()
{
Student stu((char *)"changsan",17);
cout << stu.m_name << " " << stu.m_age << endl;
AA a(10);
cout << a.m_a << " " << a.m_b << endl;
system("pause");
return 0;
}