// 在编译器的包含目录种搜索文件
#include <stdio.h>
// 优先在当前目录中搜索文件,再到编译器的包含目录搜索文件
#include “stdio.h”
常规项目用法
例子:将下面代码进行解耦(将类的具体实现方法、类的定义、整体main函数调用、三者进行分割)
解耦前原代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std; // 命名空间定义 使用C++标识符 例如:cout
//创建类
class Acc
{
//类的权限默认是私有的
private: //类权限设置为 内部访问
//属性1
string name{"None"};
//属性2
double balance{0.0};
public: // 类权限设置为 公有
//设置余额
void set_balance(double amount){
balance = amount;
};
//获取余额
double get_balance(){
return balance;
};
//设置名称
void set_name(string name);
//获取名称
string get_name();
//存款
bool deposit(double amount);
//取款
bool withdraw(double amount);
};
void Acc::set_name(string name){
this->name = name; //this指针指向当前对象
};
string Acc::get_name(){
return name;
};
bool Acc::deposit(double amount){
balance += amount;
cout << name << "刚存入" << amount << "元,现余额为" << balance << "元" << endl;
return true;
};
bool Acc::withdraw(double amount){
if (balance >= amount){
balance -= amount;
cout << name << "刚取出" << amount << "元,现余额为" << balance << "元" << endl;
return true;
} else {
cout << name << "余额不足,取款失败" <<endl;
return false;
}
};
int main()
{
//实例化 对象
Acc l1;
l1.set_name("SB1"); //设置名称
l1.set_balance(1000.0); //设置金额
cout << l1.get_name() << " 的余额为" << l1.get_balance() << "元"<< endl;
l1.deposit(200.0);
l1.withdraw(500.0);
l1.withdraw(5000.0);
return 0;
}
首先在vs coda编辑器找到配置文件,修改管理编译的配置文件 “tasks.json” ,
将"${file}",修改为"${fileDirname}/*.cpp"。
(一)头文件
将类的定义放在:xxx.h的文件中,例如:Accout.h
格式如下:
#ifndef ACCOUT_H // #ifndef的意义:防止头文件被重复包含和编译
#define ACCOUT_H // #define 同上
// 代码内容
#endif // 同上
Accout.h 内容如下:
注意有些需要加上 std::
#ifndef ACCOUT_H
#define ACCOUT_H
#include <string>
//创建类
class Acc
{
//类的权限默认是私有的
private: //类权限设置为 内部访问
//属性1
std::string name{"None"};
//属性2
double balance{0.0};
public: // 类权限设置为 公有
//设置余额
void set_balance(double amount){
balance = amount;
};
//获取余额
double get_balance(){
return balance;
};
//设置名称
void set_name(std::string name);
//获取名称
std::string get_name();
//存款
bool deposit(double amount);
//取款
bool withdraw(double amount);
};
#endif // ACCOUT_H
(二)类的具体功能
注意:导入自定义头文件后,调用类别方法时需要加上类别名。
有些需要加上 std::
#include <iostream>
#include "Accout.h"
void Acc::set_name(std::string name){
this->name = name; //this指针指向当前对象
};
std::string Acc::get_name(){
return name;
};
bool Acc::deposit(double amount){
balance += amount;
std::cout << name << "刚存入" << amount << "元,现余额为" << balance << "元" << std::endl;
return true;
};
bool Acc::withdraw(double amount){
if (balance >= amount){
balance -= amount;
std::cout << name << "刚取出" << amount << "元,现余额为" << balance << "元" << std::endl;
return true;
} else {
std::cout << name << "余额不足,取款失败" <<std::endl;
return false;
}
};
(三)main函数
#include <iostream>
#include "Accout.h"
using namespace std; // 命名空间定义 使用C++标识符 例如:cout
int main()
{
//实例化 对象
Acc l1;
l1.set_name("SB1"); //设置名称
l1.set_balance(1000.0); //设置金额
cout << l1.get_name() << " 的余额为" << l1.get_balance() << "元"<< endl;
l1.deposit(200.0);
l1.withdraw(500.0);
l1.withdraw(5000.0);
return 0;
}