cppTest-4.0:结构体

本文介绍了C++中结构体的特性和用法,包括与C语言结构体的区别,如支持成员函数、简化变量声明等,并通过实例展示了结构体的应用,如实现简单的时钟更新与显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 *cppTest-4.0:结构体
 *
 *c++对比比c的结构体:
 *1、多了函数成员!
 *2、定义结构体变量时不用在前面加struct关键字!
 *3、结构体是一种特殊的类,因此定义结构体类型时不能初始化变量!这个与c语言相同!详情请看如下例子。 
 *author 炜sama
 */
#include<iostream.h>
#include<conio.h>
#define	TIMES	12800000
struct	time{
	int	hours;
	int	minutes;
	int	seconds;
};//分号不能漏!!!
void update(struct time *t);
void display(struct time *t);
void delay();
int main()
{
	struct test{
		int i;
		//int i1=0;//错误! 
		//const int i2=0;//错误! 
		//static const int i3=0;//错误! 
		char c;
		void print(){cout<<i<<"--"<<c<<endl;};//c++的结构体可以有函数成员!默认是public的
	};
	test t;//c++才支持这样定义结构体变量!如果是c语言的话应该如此:struct test t;
	t.i=10;
	t.c='c';
	cout<<t.i<<endl;
	cout<<t.c<<endl;
	t.print();

	struct time t1;
	t1.hours=0;
	t1.minutes=0;
	t1.seconds=0;
	for(;!kbhit();){
		update(&t1);
		display(&t1);
	}
	
	return 0;
}
void update(struct time *t)
{
	t->seconds++;
	if(t->seconds==60){
		t->seconds=0;
		t->minutes++;
	}
	if(t->minutes==60){
		t->minutes=0;
		t->hours++;
	}
	if(t->hours==24) t->hours=0;
	delay();
}
void display(struct time *t)
{
	cout<<t->hours<<":"<<t->minutes<<":"<<t->seconds<<endl;
}
void delay()
{
	long int i;
	for(i=0;i<3*TIMES;i++);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值