当前位置: 首页 > news >正文

C++指针、指针函数、函数指针、类指针

1、指针变量

#include <iostream>using namespace std;int main ()
{int  var = 20;   // 实际变量的声明int  *ip;        // 指针变量的声明ip = &var;       // 在指针变量中存储 var 的地址cout << "Value of var variable: ";cout << var << endl;// 输出在指针变量中存储的地址cout << "Address stored in ip variable: ";cout << ip << endl;// 访问指针中地址的值cout << "Value of *ip variable: ";cout << *ip << endl;return 0;
}

2、指针函数

#include <iostream>
#include <ctime>using namespace std;// 在写函数时应习惯性的先声明函数,然后在定义函数
void getSeconds(unsigned long *par);int main ()
{unsigned long sec;getSeconds( &sec );// 输出实际值cout << "Number of seconds :" << sec << endl;return 0;
}void getSeconds(unsigned long *par)
{// 获取当前的秒数*par = time( NULL );return;
}

3、函数指针

#include <iostream>
#include <ctime>
#include <cstdlib>using namespace std;// 要生成和返回随机数的函数
int * getRandom( )
{static int  r[10];// 设置种子srand( (unsigned)time( NULL ) );for (int i = 0; i < 10; ++i){r[i] = rand();cout << r[i] << endl;}return r;
}// 要调用上面定义函数的主函数
int main ()
{// 一个指向整数的指针int *p;p = getRandom();for ( int i = 0; i < 10; i++ ){cout << "*(p + " << i << ") : ";cout << *(p + i) << endl;}return 0;
}

4、类指针

#include <iostream>using namespace std;class Box
{public:// 构造函数定义Box(double l=2.0, double b=2.0, double h=2.0){cout <<"Constructor called." << endl;length = l;breadth = b;height = h;}double Volume(){return length * breadth * height;}private:double length;     // Length of a boxdouble breadth;    // Breadth of a boxdouble height;     // Height of a box
};int main(void)
{Box Box1(3.3, 1.2, 1.5);    // Declare box1Box Box2(8.5, 6.0, 2.0);    // Declare box2Box *ptrBox;                // Declare pointer to a class.// 保存第一个对象的地址ptrBox = &Box1;// 现在尝试使用成员访问运算符来访问成员cout << "Volume of Box1: " << ptrBox->Volume() << endl;// 保存第二个对象的地址ptrBox = &Box2;// 现在尝试使用成员访问运算符来访问成员cout << "Volume of Box2: " << ptrBox->Volume() << endl;return 0;
}
http://www.lryc.cn/news/150818.html

相关文章:

  • 图:最短路径问题(BFS算法,Dijkstra算法,Floyd算法)
  • 栈和队列篇
  • 分享一个vue-slot插槽使用场景
  • Qt应用开发(基础篇)——进度对话框 QProgressDialog
  • 基于SpringBoot2的后台业务管理系统
  • Jmeter(三十):并发测试(设置集合点)
  • Flink的checkpoint是怎么实现的?
  • ubuntu上安装nginx
  • 9. 微积分 - 导数
  • 滑动窗口系列1-达标子数组
  • 电视显示技术及价格成本对比(2023年)
  • 浅谈 Pytest+HttpRunner 如何展开接口测试!
  • vue自定义事件 div 拖拽方法缩小
  • 使用实体解析和图形神经网络进行欺诈检测
  • vue中axios请求篇
  • Springboot2.0 上传图片 jar包导出启动(第二章)
  • 添加YDNS免费的ipv6动态域名解析
  • 爬虫异常处理之如何处理连接丢失和数据存储异常
  • KVM虚拟化ubuntu
  • 模拟电子技术基础学习笔记三 PN结
  • java基础-----第七篇
  • useEffect 不可忽视的 cleanup 函数
  • vue3:使用:批量删除功能
  • Scala中的样例类和样例对象和JAVA存根类
  • 【0218】当SIGQUIT kill掉stats collector后,stats collector如何保存最终统计数据
  • httplib 与 json.hpp 结合示例
  • RK3288安卓7.1开机上电到显示logo需要在3s内完成
  • Maven之hibernate-validator 高版本问题
  • C++--动态规划其他问题
  • PostgreSQL 查询语句大全