- 设计一个类
- class + 类名 { 成员变量 成员函数 }
- 将属性和行为作为一个整体,来表现生活中的事物
- 将属性和行为 加以权限控制
- 访问权限
- 公共权限 public 类内 类外 都可以访问
- 私有权限 private 类内可以访问 类外不可以访问
- 保护权限 protected类内可以访问 类外不可以访问
- class 默认权限 私有权限 而 struct默认权限是 公共权限
- 通过类创建对象过程 称为 实例化对象
- 函数的默认参数和占位参数
- 默认参数
- 可以给函数的形参添加默认值
- 语法 形参 类型 变量 = 默认值
- int func(int a, int b = 10 , int c = 10)
- 注意事项 ,如果有一个位置有了默认参数,那么从这个位置起,从左到右都必须有默认值
- 函数的声明和实现 只能有一个 提供默认参数,不可以同时加默认参数
- 占位参数
- 只写一个类型进行占位,调用时候必须要传入占位值
- void func2(int a , int = 1)
- 占位参数也可以有默认值
- 默认参数
- 函数重载
- 满足条件
- 同一个作用域下
- 函数名称相同
- 函数参数个数、类型、顺序不同
- 函数的返回值 不可以作为重载条件
- 注意事项
- 加const和不加const的引用可以作为重载条件
- 函数重载碰到默认参数 注意避免二义性出现
- 满足条件
- extern C
- 用途:在C++中调用C语言文件
- C++中有函数重载,会对函数名称做修饰,导致调用C语言的函数链接失败
- 利用extern C可以解决问题
- 方法1:
- 在C++代码中加入
- 告诉编译器 show函数用C语言方式 做链接
- //extern "C" void show();
- 方法2:
- 在C语言的头文件中加入6行代码
- #ifdef __cplusplus // 两个下划线 __ c plus plus
- extern "C" {
- #endif
- #ifdef __cplusplus // 两个下划线 __ c plus plus
- }
- #endif
- 方法1:
示例
#include <iostream>
#include<string>
#include"test.h"
using namespace std;
const double PI = 3.1415926;
// 内联函数,在函数前加inline,以空间换时间,可以避免预处理中宏的一些问题
//inline void func
//class类中函数默认为内联函数
//以下情况会将内联函数当层普通函数处理
//存在循环
//过多判断
//函数过于庞大
//不能对函数取地址
class circle {
//私有属性,类内使用
private:
int r;
//公有属性,随便用
public:
int getR() {
return this->r;
}
void setR(int data) {
this->r = data;
}
double calc() {
return this->r*PI;
}
//受保护属性,类内和子类
protected:
};
//引用c语言中方法
//extern "C" void show();
//函数带默认参数,不写函数名为站位符
//a后面要全带默认值
//void _test_int_int_int_int_int(){}编译时会对函数名称从新修饰
void test(int a1,int,int a=3,int b=4,int=6) {
show();
}
class Person {
private:
string name;
int age;
string car;
int deposit;
public:
//构造函数,类创建时执行
Person(string name, int age, string car, int deosit);
//析构函数,类释放前执行
~Person();
void showPersonInfo() {
cout << "name:" << this->name << endl;
cout << "age:" << this->age << endl;
cout << "car:" << this->car << endl;
cout << "deposit:" << this->deposit << endl;
}
protected:
};
Person::Person(string name,int age,string car,int deposit) {
this->name = name;
this->age = age;
this->car = car;
this->deposit = deposit;
}
Person::~Person() {
cout<<"reuslt"<<endl;
}
//函数重载,根据函数参数重载,不可以根据返回值重载(返回值可以不要)
void test() {
Person* p = new Person("Andy", 21, "保时捷", 9999);
p->showPersonInfo();
delete p;
}
int main()
{
circle* c = new circle();
c->setR(4);
cout <<"r:" << c->getR() << endl;
cout << c->calc()<< endl;
test(3,4,5);
test();
system("pause");
return EXIT_SUCCESS;
}
test.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include<stdio.h>
void show();
void hide();
#ifdef __cplusplus
}
#endif // __cplusplus