C++ 数据共享与保护学习记录【代码】

2024-06-08 00:12

本文主要是介绍C++ 数据共享与保护学习记录【代码】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一.项目一

1.头文件.h

//A.h
#pragma once
//防止头文件被重复包含(重复包含会被重复编译,也就是该类会被重复定义)
#ifndef HEAD_H
//等价于( #if !defined(HEAD_H) )
//defined是一个预处理操作符,相当于一个表达式
#define HEAD_H
class A
{
public:static void f(A a);static void show();//构造函数//只能在初始化列表初始化常数据成员A(int x, int conx) :x(x), conx(conx) { x2++; }
private:int x;static int x2;const int conx;
};
//必须有结束指令
#endif
//Clock.h
#pragma once
#include<string>
using namespace std;
class Clock
{
public:Clock();void setTime(int newH, int newM, int newS, string newN);void showTime() const;//友元类friend class Point;
private:int hour, minute, second;string name;//类的静态常量如果有整数类型或枚举类型,可以在定义中指定常量值(不分配内存,只是简单替换)static const int b = 10;
};
//内联函数不用分配内存(定义在头文件中)
inline int add(int a, int b) {return a + b;
}
//Point.h
#pragma once
#include"Clock.h"
class Point
{
public:Point(int x = 0, int y = 0) :x(x), y(y) {}int getX() const{ return x; }int getY() const{ return y; }//友元函数friend float dist(Point& p1, Point& p2);//作为Clock的友元类,可以访问其私有成员void show_Clock(Clock& c);
private:int x, y;
};

2.源文件.cpp

//A.cpp
#include "A.h"
#include<iostream>
using namespace std;//外部变量只能放在.cpp下,不能在.h下(定义型声明)(文件作用域)
extern int j = 20;//外部函数(不声明,文件作用域)
void showing(){cout << "Hello Extern Function!--NOT--DEFINE" << endl;
}
//外部函数(声明为全局)
extern void showed() {cout << "Hello Extern Function!--DEFINE" << endl;
}
//静态函数(不能被其他编译单元引用)(静态生存期)
void static shows() {cout << "Hello Static Function!" << endl;
}//必须在类外使用类名进行定义式声明(初始化)
int A::x2 = 0;void A::f(A a) {// cout << x; //不能在静态成员函数中直接访问非静态成员,必须与特定成员相对cout << "a.x:" << a.x << endl;cout << "x2:" << x2 << endl; // 可以直接访问静态成员}void A::show() {cout << "x2:" << x2 << endl;
}
//Clock.cpp
#include "Clock.h"
#include<iostream>
#include<string>
using namespace std;
//文件作用域(没有声明,但是在main函数中引用性声明,值也相同)
int i = 10;
Clock::Clock() :hour(0), minute(0), second(0) {cout << "调用构造函数" << endl;
}void Clock::setTime(int newH, int newM, int newS, string newN) {name = newN;hour = newH;minute = newM;second = newS;
}
void Clock::showTime() const {cout << hour << ":" << minute << ":" << second << endl;cout << name << endl;
}
//Point.cpp
#include "Point.h"
#include<iostream>
#include<cmath>
using namespace std;
//友元函数实现
float dist(Point& p1, Point& p2) {double x = p1.x - p2.x;double y = p1.y - p2.y;//static_cast是一种类型转换运算符,用于在编译时进行类型转换return static_cast<float>(sqrt(x * x + y * y));
}void Point::show_Clock(Clock& c) {cout << "This is showed by Point" << this->x << " " << this->y << endl;cout << c.name << endl;
}

3.主函数.cpp

//main.cpp
#include"Clock.h"
#include"A.h"
#include"Point.h"
#include<iostream>
#include<string>
using namespace std;
// 定义未指定初值的基本类型静态生存期变量,会被以0值初始化
// 声明具有静态生存期的对象
Clock globalClock;int main() {//生存期cout << "生存期" << endl;cout << "First:" << endl;globalClock.showTime();globalClock.setTime(8, 30, 30, "theclock");Clock myClock(globalClock);cout << "Second:" << endl;myClock.showTime();//静态成员  A a1(100,100);A a2(99,100);//调用静态成员函数cout << "调用静态成员函数" << endl;A::f(a1);A::f(a2);A::show();//友元函数cout << "友元函数" << endl;Point myp1(1, 1), myp2(4, 5);cout << "The distance is:" << endl;cout << dist(myp1, myp2);//友元类//友元关系:不可传递,单向,不被继承//友元函数不仅可以是普通的函数,也可以是另外一个类的成员函数cout << "通过友元类输出私有类成员:" << endl;myp1.show_Clock(myClock);//调用内联函数cout << "4 + 5 = " << add(4, 5) << endl;//外部变量extern定义(引用性声明)extern int i;cout << "外部变量 i = " << i << endl;//在源文件中声明后还要再声明,此时值一致extern int j;cout << "外部变量 j = " << j << endl;//外部函数(使用要包含文件+函数声明)void showing();//extern void showing();//也可showing();void showed();showed();//不能访问其他编译单元静态函数//void shows();//shows();return 0;
}

4.输出

调用构造函数
生存期
First:
0:0:0Second:
8:30:30
theclock
调用静态成员函数
a.x:100
x2:2
a.x:99
x2:2
x2:2
友元函数
The distance is:
5通过友元类输出私有类成员:
This is showed by Point1 1
theclock
4 + 5 = 9
外部变量 i = 10
外部变量 j = 20
Hello Extern Function!--NOT--DEFINE
Hello Extern Function!--DEFINE

二.个人银行账户管理系统

(主要添加静态数据成员static,常成员const,条件预编译,并且实现头文件源文件文件分离)

1.头文件.h

//account.h
#pragma once
//条件预编译指令
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
class SavingsAccount
{
private:int id; //账号double balance; //余额double rate; //存款的年利率int lastDate; //上次变更余额的时期double accumulation; //余额按日累加之和static double total;	//所有账户总余额//记录一笔账, date为日期, amount为金额, desc为说明void record(int date, double amount);//获得到指定日期为止的存款金额按日累积值double accumulate(int date) const {return accumulation + balance * (date - lastDate);}
public:SavingsAccount(int date, int id, double rate); //构造函数int getId() const { return id; }double getBalance() const { return balance; }double getRate() const { return rate; }static double getTotal() { return total; }void deposit(int date, double amount); //存入现金void withdraw(int date, double amount); //取出现金//结算利息,每年1月 1日调用一次该函数void settle(int date);//显示账户信息void show() const;//友元函数friend void show_items(SavingsAccount& s1);//友元类friend class AnotherAccount;
};
#endif
//AnotherAccount.h
#pragma once
#include"account.h"
class AnotherAccount
{
//成员函数可以访问SavingsAccount的保护和私有成员
private:SavingsAccount S1;SavingsAccount S2;
public:AnotherAccount(SavingsAccount& s1,SavingsAccount& s2):S1(s1),S2(s2) {}void showing() const;
};

2.源文件.cpp

//account.cpp
#include "account.h"
#include<iostream>
using namespace std;// 一定要在类外初始化静态本地变量,不然会报错
double SavingsAccount::total = 0;// 友元函数实现
void show_items(SavingsAccount& s1) {cout << "id:" << s1.id << "	  balance:" << s1.balance << " 	 lastDate:" << s1.lastDate << endl;
}//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(int date, int id, double rate): id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {cout << date << "\t#" << id << " is created" << endl;
}
void SavingsAccount::record(int date, double amount) {accumulation = accumulate(date);lastDate = date;amount = floor(amount * 100 + 0.5) / 100; //保留小数点后两位(四舍五入)balance += amount;total += amount;cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
}
void SavingsAccount::deposit(int date, double amount) {record(date, amount);
}
void SavingsAccount::withdraw(int date, double amount) {if (amount > getBalance())cout << "Error: not enough money" << endl;elserecord(date, -amount);
}
void SavingsAccount::settle(int date) {double interest = accumulate(date) * rate / 365; //计算年息if (interest != 0)record(date, interest);accumulation = 0;
}
void SavingsAccount::show() const{cout << "#" << id << "\tBalance: " << balance;
}
//AnotherAccount.cpp
#include "AnotherAccount.h"
#include<iostream>
using namespace std;
//访问SavingsAccount的私有成员
void AnotherAccount::showing() const{if (S1.balance > S2.balance) {cout << "The bigger is:" << S1.id << "   balance:" << S1.balance << endl;}else if (S1.balance < S2.balance) {cout<< "The bigger is:" << S2.id << "   balance:" << S2.balance << endl;}else {cout << "No one bigger than the other" << endl;}
}

3.主函数.cpp

//5-11.cpp
#include<iostream>
#include"account.h"
#include"AnotherAccount.h"
using namespace std;int main() {//建立几个账户cout << "建立账户:" << endl;SavingsAccount sa0(1, 1234567, 0.02);SavingsAccount sa1(5, 7654321, 0.025);//几笔账目cout << "记账:" << endl;sa0.deposit(5, 670000);sa1.deposit(6, 700000);sa0.deposit(60, 5500);sa1.withdraw(70, 4000);//开户后第100天到了银行的计息日,结算所有账户的年息cout << "结息:" << endl;sa0.settle(100);sa1.settle(100);//输出各个账户信息cout << "输出各个账户信息:" << endl;sa0.show();cout << endl;sa1.show();cout << endl;cout << "利用静态本地变量const唯一初始化性输出total:" << endl;cout << "Total:" << SavingsAccount::getTotal() << endl;//利用友元函数输出账户信息cout << "利用友元函数输出账户信息:" << endl;show_items(sa0);show_items(sa1);//友元类cout << "友元类访问私有成员然后输出:" << endl;AnotherAccount s1(sa0,sa1);s1.showing();return 0;
}

4.输出

建立账户:
1       #1234567 is created
5       #7654321 is created
记账:
5       #1234567        670000  670000
6       #7654321        700000  700000
60      #1234567        5500    675500
70      #7654321        -4000   696000
结息:
100     #1234567        3499.73 679000
100     #7654321        4498.63 700499
输出各个账户信息:
#1234567        Balance: 679000
#7654321        Balance: 700499
利用静态本地变量const唯一初始化性输出total:
Total:1.3795e+06
利用友元函数输出账户信息:
id:1234567        balance:679000         lastDate:100
id:7654321        balance:700499         lastDate:100
友元类访问私有成员然后输出:
The bigger is:7654321   balance:700499

三.其他

1.限定作用域的enum枚举类

//限定作用域的enum枚举类
#include<iostream>
#include<string>
using namespace std;
enum color { red, yellow, green };
//enum color1 { red, yellow, green }; //错误,枚举类型不能重复定义
enum class color2 { red, yellow, green }; // 正确 限定作用域的枚举元素被隐藏
color c = red;
//color2 c1 = red; // color类型的值不能用来初始化color2类型实体
color c2 = color::red; // 显式的访问枚举元素
color2 c3 = color2::red; // 使用color2枚举元素
struct SColor {enum color { red, yellow, green };
};
SColor::color c = SColor::red; // 正确使用未限定作用域的枚举元素

2.常成员函数举例

//常成员函数举例
#include<iostream>
using namespace std;class R {
public:R(int r1, int r2) :r1(r1), r2(r2) {}void print();void print() const;
private:int r1, r2;
};void R::print() {cout << r1 << "---" << r2 << endl;
}void R::print() const {cout << r1 << "+++" << r2 << endl;
}int main() {R a(5, 4);a.print(); //调用普通函数成员const R b(20, 25);b.print(); //调用常函数成员return 0;
}
//输出
5---4
20+++25

这篇关于C++ 数据共享与保护学习记录【代码】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1040702

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

Java集合之Iterator迭代器实现代码解析

《Java集合之Iterator迭代器实现代码解析》迭代器Iterator是Java集合框架中的一个核心接口,位于java.util包下,它定义了一种标准的元素访问机制,为各种集合类型提供了一种统一的... 目录一、什么是Iterator二、Iterator的核心方法三、基本使用示例四、Iterator的工

Java 线程池+分布式实现代码

《Java线程池+分布式实现代码》在Java开发中,池通过预先创建并管理一定数量的资源,避免频繁创建和销毁资源带来的性能开销,从而提高系统效率,:本文主要介绍Java线程池+分布式实现代码,需要... 目录1. 线程池1.1 自定义线程池实现1.1.1 线程池核心1.1.2 代码示例1.2 总结流程2. J

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②

Vue实现路由守卫的示例代码

《Vue实现路由守卫的示例代码》Vue路由守卫是控制页面导航的钩子函数,主要用于鉴权、数据预加载等场景,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录一、概念二、类型三、实战一、概念路由守卫(Navigation Guards)本质上就是 在路

uni-app小程序项目中实现前端图片压缩实现方式(附详细代码)

《uni-app小程序项目中实现前端图片压缩实现方式(附详细代码)》在uni-app开发中,文件上传和图片处理是很常见的需求,但也经常会遇到各种问题,下面:本文主要介绍uni-app小程序项目中实... 目录方式一:使用<canvas>实现图片压缩(推荐,兼容性好)示例代码(小程序平台):方式二:使用uni

JAVA实现Token自动续期机制的示例代码

《JAVA实现Token自动续期机制的示例代码》本文主要介绍了JAVA实现Token自动续期机制的示例代码,通过动态调整会话生命周期平衡安全性与用户体验,解决固定有效期Token带来的风险与不便,感兴... 目录1. 固定有效期Token的内在局限性2. 自动续期机制:兼顾安全与体验的解决方案3. 总结PS

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

Python屏幕抓取和录制的详细代码示例

《Python屏幕抓取和录制的详细代码示例》随着现代计算机性能的提高和网络速度的加快,越来越多的用户需要对他们的屏幕进行录制,:本文主要介绍Python屏幕抓取和录制的相关资料,需要的朋友可以参考... 目录一、常用 python 屏幕抓取库二、pyautogui 截屏示例三、mss 高性能截图四、Pill