📄 c++编程思想 -- 第2章 笔记(5).txt
字号:
作者:rick1126
email: rickzhang@sina.com
日期:2001-7-18 9:45:25
2.9 头文件形式
【头文件在C++的重要性】
. 头文件用来放置专门的信息 -- 声明
. C++ 不允许在没有声明就直接实现
. 头文件是库的开发者和用户之间的合同, 该合同描述数据结构, 说明函数的参数和返回值. 包括类成员.
. C++ 要求强制执行该合同
【头文件需要解决的问题】
. 将什么置于头文件 -- 声明和部分实现
. 重复声明问题
#ifndef ...
#define ...
...
#endif//...
【项目使用头文件】
. 模块头文件通常用以存放项目范围有效的数据结构和系统过程声明
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2.10 嵌套结构
【栈数据结构模拟】
. 其实规定栈元素嵌套在栈结构内部, 很好的将相关数据"圈地"起来, 放置了过分使用公共名字空间, 也更符合逻辑
. 操作符::就可以表示范围, 没有任何前缀就表示全局空间, 否则一般C++总是自动匹配最近活动范围
【相关代码】
. 其实这都是书上的, 我就替大家抄了.
//nested.h
#ifndef NESTED_H_200107180917
#define NESTED_H_200107180917
struct stack{
struct link{
void* data;
link* next;
void initialize( void* Data, link* Next );
}*head;
void initialize( );
void push( void* Data );
void* peek( );
void* pop( );
void cleanup( );
};
#endif//NESTED_H_200107180917
// nested.cpp
#include "stdafx.h"
#include "stdlib.h"
#include "assert.h"
#include "nested.h"
void stack::link::initialize( void* Data, link* Next )
{
data = Data;
next = Next;
}
void stack::initialize( ) { head = 0; }
void stack::push( void* Data )
{
link* newlink = ( link* )malloc( sizeof( link ) );
assert( newlink );
newlink->initialize( Data, head );
head = newlink;
}
void* stack::peek( ) { return head->data; }
void* stack::pop( )
{
if ( head==0 ) return 0;
void* result = head->data;
link* oldHead = head;
head = head->next;
free( oldHead );
return result;
}
void stack::cleanup( )
{
link* cursor = head;
while ( head ){
cursor = cursor->next;
free( head->data );
free( head );
head = cursor;
}
}
// ch2_stack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "nested.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "assert.h"
#define BUFFERSIZE 100
int main(int argc, char* argv[])
{
stack textlines;
FILE* file;
char* s;
char buf[BUFFERSIZE];
assert( argc == 2 );
textlines.initialize( );
file = fopen( argv[1], "r" );
assert( file );
while ( fgets( buf, BUFFERSIZE, file ) ){
char* string = (char*)malloc(strlen(buf) + 1 );
assert( string );
strcpy( string, buf );
textlines.push( string );
}
while ( ( s=(char*)textlines.pop() )!=0 ){
printf( "%s", s );
free ( s );
}
textlines.cleanup();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -