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

相关文章

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

C++中RAII资源获取即初始化

《C++中RAII资源获取即初始化》RAII通过构造/析构自动管理资源生命周期,确保安全释放,本文就来介绍一下C++中的RAII技术及其应用,具有一定的参考价值,感兴趣的可以了解一下... 目录一、核心原理与机制二、标准库中的RAII实现三、自定义RAII类设计原则四、常见应用场景1. 内存管理2. 文件操

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

统一返回JsonResult踩坑的记录

《统一返回JsonResult踩坑的记录》:本文主要介绍统一返回JsonResult踩坑的记录,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录统一返回jsonResult踩坑定义了一个统一返回类在使用时,JsonResult没有get/set方法时响应总结统一返回

C++作用域和标识符查找规则详解

《C++作用域和标识符查找规则详解》在C++中,作用域(Scope)和标识符查找(IdentifierLookup)是理解代码行为的重要概念,本文将详细介绍这些规则,并通过实例来说明它们的工作原理,需... 目录作用域标识符查找规则1. 普通查找(Ordinary Lookup)2. 限定查找(Qualif