C++ 面向对象

2021-03-10  本文已影响0人  ZoranLee

C++ 与 C语言 区别

1、C语言的标准支持:#include<stdio.h>
2、C++标准支持:#include<iostream>

C++

using namespacing std; /
std:cout<<"C++语言"<<std:endl;
可以简写为
cout<<"c++语言学习"<<endl
image.png
cout<<"字符"<<endl;
cout<<"铁头功\n"
      <<"金刚腿\n"
      <<"铁布衫\n";

常量

int main(){
const int number = 100;
int *numP = &number;
*numP = 1000;
printf("%d\n",number);//1000 值已经修改了
return 0;
}
const int number = 100;
//int *numP = &number; 编译的时候 就会报错
//*numP = 1000;编译的时候 就会报错
printf("%d\n",number);//1000 值已经修改了

引用

void numberChange(int * number1,int * number2){
  int temp = 0;
  temp = * number1;
 *number1 = * number2;
*number2 = temp;
}
int main(){
int number1 = 10;
int number2 = 20;
numberChange(&number1,&number2);
return 0;
}

原理:


image.png

2、C++ 的引用 互换

void numberChange2(int & number1, int & number2){
int temp = 0;
temp = number1;
number1= number2;
number2 = temp;
}
int mian(){
int number1 =10;
int number2 = 20;
numberChange2(number1,number2);
return 0;
}

原理图

image.png

3、常量引用

typedef struct {
  char name[20];
  int age;
}Student;

image.png

4、函数重载

image.png

2、头文件只写申明不写实现

#include<iostream>
using namespace std;
class Student{
private :
  char * name;
  int age;
public:
  void setAge(int age);//声明函数
  void setName(char *age);
  int getAge();
  char * getName( );//声明函数
}

具体实现

.c .cpp
#include "Student.h" //引入头文件
void Student::setAge(int age){
this->age = age;
}
void Student::setName(char * name){
this->name = name;
}


Student * student1;//栈空间
student1.setAge(99);
student1.setName("lisa");
cout<<"name:"<<student1.getName()<<",age:"<<student1.getAge()<<endl;

//堆空间
Student * student2 = new Student();
student2 ->setAge(80);
student2->setName("lisa");
delete student2;//必须手动释放对象student2
//不能用free(student2)
上一篇下一篇

猜你喜欢

热点阅读