C++学习七 C++实现add(1)(2)(3)
2024-08-29 23:23:24
一、代码实现:
class Yoba
{
public:
Yoba(int n) : _n(n) {}
Yoba operator() (int n) { return Yoba(_n + n); }
bool operator== (int n) { return _n == n; }
int operator+ (int n) { return _n + n; }
int operator- (int n) { return _n - n; }
friend bool operator== (int n, const Yoba & y) { return n == y._n; } private:
int _n;
}; auto add(int n)
{
return Yoba(n);
}
这里对于对于功能实现add(1)(2)(3), 这里用到了()符号的重载。
二、这里对于类的实现做一些讲解:
这里有一个例子:
class CountPeople
{
public:
//构造函数
CountPeople() :number(), _size(), T()
{
cout << "number of the C is " << number << endl;
}
//析构函数
~CountPeople()
{}
//初始化参数列表的结构
CountPeople(int n) :number(n)
{
cout << "number is "<<number<<endl;
}
//方法接口,operator 重载操作符()
CountPeople operator() (int n)
{
return CountPeople(number + n);
}
int operator+ (int n)
{
return number + n;
}
friend bool operator== (const CountPeople& y,int n ) { return n == y.number; }
// bool operator== (int n) { return n == number; }
int GetNumber();
int GetSize();
private:
int _size;
int number;
int T;
};
上面是一个类的结构。
对于一些方法,可以在类的外部实现。
int CountPeople::GetNumber()
{
return number;
}
int CountPeople::GetSize()
{
return _size;
}
一个类的结构:
构造函数
析构函数
私有变量
方法。
三、如果需要将类不放在main里面,那么在cpp里面的分布为:
cpp | main.cpp | usage.cpp | usage.hpp |
内容 |
#include "usage.hpp" int main(void) { return 0; } |
类的方法具体内容 | 类的定义 |
具体分布如下:
四、CountPeople(1)(3)的调用过程
先是调用CountPeople(1)
然后调用()重载函数
再调用CountPeople(3)
最新文章
- zookeeper源码分析之六session机制
- elk平台搭建
- 【转】NoSQL初探之人人都爱Redis:(1)Redis简介与简单安装
- mybatis一对多查询
- Oracle 数据泵文件
- 初学ExtJs 表格显示后台数据
- Poj 2478-Farey Sequence 欧拉函数,素数,线性筛
- 206.反转单列表 Reverse Linked List
- 一篇文章介绍GItHub的基础使用
- IOC容器在web容器中初始化过程——(二)深入理解Listener方式装载IOC容器方式
- 用js来实现那些数据结构07(链表01-链表的实现)
- Java实现堆的封装,进行插入,调整,删除堆顶以完成堆排序实例
- Springboot2注解使用Mybatis动态SQL
- io系列之其他事项
- Java学习笔记36(jdbc快速入门)
- matplotlib 28原则
- 第三部分:Android 应用程序接口指南---第二节:UI---第八章 Toast通知
- linux文件系统(一)
- 在Ubuntu14.04 64bit上搭建单机Spark环境,IDE为Intelli IDEA
- 常用CSS实例