1. 程式人生 > >《C++程式設計思想》(第二版)第3章 C++中的C(筆記、習題及答案)(一)

《C++程式設計思想》(第二版)第3章 C++中的C(筆記、習題及答案)(一)

一.總結本章的內容:

1.如果宣告指標是void* ,它意味著任何型別的地址都可以間接引用那個指標(而如果宣告int*,則只能對int型變數的地址間接引用那個指標)。一旦我們間接引用一個void*,就會丟失關於型別的資訊。這意味著在使用前,必須轉換為正確的型別。

2.Static變數使得區域性變數的值在程式的整個生命期裡仍然存在,其優點是在函式範圍之外它是不可用的,所以不可能被輕易改變。

3.內部連結意味著只對正在編譯的檔案建立空間,外部連線意味著所有被編譯過的檔案建立一片單獨的儲存空間。

4.顯示轉換語法:

(1).static_cast:用於“良性”和“適度良性”轉換,包括不用強制轉換(例如自動型別轉換);

(2).const_cast:對“const”和/或“volatile”進行轉換;

(3).reinterpret_cast:轉換為完全不同的意思。為了安全使用它,關鍵必須轉換回原來的型別。轉換成的型別一般只能用於位操作,否則就是為了其他隱祕的目的。這是所有轉換中最危險的。

(4).dynamic_cast:用於型別安全的向下轉換。

5.asm關鍵字:是一種轉義機制,允許在C++程式中寫彙編程式碼。在彙編程式程式碼中經常可以引用C++的變數,這意味著可以方便的和C++程式碼通訊,且限定彙編程式碼只能用於必要的高效調整,或使用特殊的處理器指令。

6.想給程式傳遞命令列引數時,C和C++的函式main()有特殊的引數表,其形式如:int main(int argc, char* argv[]);

   argv[0]是程式本身的路徑和名字。

7.複雜變數和函式定義:

(1).void *(*(*fp1)(int))[10];

      *fp1是一個指向函式的指標,該函式接受一個整型引數並返回一個指向含有10個void指標陣列的指標。

(2).float (*(*fp2)(int,int,float))(int);

       *fp2是一個指向函式的指標,該函式接收三個引數(int、int和float)且返回一個指向函式的指標,該函式接受一個整型引數並返回一個float。

(3).typedef double (*(*(fp3)())[10])();

       fp3是一個指向函式的指標,該函式無引數,且返回一個含有10個指向函式指標陣列的指標,這些函式不接受引數且返回double值。

(4).int (*(*f4())[10])();

       f4是一個返回指標的函式,該指標指向含有10個函式指標的陣列,這些函式返回整型值。

二.和習題有關的函式:

     Ifthen.cpp

#include <iostream>
using namespace std;

int main()
{
	int i;
	cout<<"type a number and 'Enter'"<<endl;
	cin>>i;
	if(i>5)
	{
		cout<<"It's greater than 5"<<endl;
	}
	else
	{
		if(i<5)
		{
			cout<<"It's less than 5"<<endl;
		}
		else
		{
			cout<<"It's equal to 5"<<endl;
		}
	}
	cout<<"type a number and 'Enter'"<<endl;
	cin>>i;
	if(i<10)
	{
		if(i>5)
		{
			cout<<"5<i<10"<<endl;
		}
		else
		{
			cout<<"i<=5"<<endl;
		}
	}
	else
	{
		cout<<"i>=10"<<endl;
	}

	return 0;
}


Menu.cpp

#include <iostream>
using namespace std;

int main()
{
	char c;
	while(true)
	{
		cout<<"MAIN MENU:"<<endl;
		cout<<"l:left,r:right,q:quit->";
		cin>>c;
		if(c == 'q')
		{
			break;
		}
		if(c == 'l')
		{
			cout<<"LEFT MENU:"<<endl;
			cout<<"select a or b:";
			cin>>c;
			if(c == 'a')
			{
				cout<<"you choose 'a'"<<endl;
				continue;
			}
			if(c == 'b')
			{
				cout<<"you choose 'b'"<<endl;
				continue;
			}
			else
			{
				cout<<"you don't choose a or b"<<endl;
				continue;
			}
		}
		if(c == 'r')
		{
			cout<<"RIGHT MENU:"<<endl;
			cout<<"select c or d:";
			cin>>c;
			if(c == 'c')
			{
				cout<<"you choose 'c'"<<endl;
				continue;
			}
			if(c == 'd')
			{
				cout<<"you choose 'd'"<<endl;
				continue;
			}
			else
			{
				cout<<"you don't choose c or d"<<endl;
				continue;
			}
		}
		cout<<"you must type l or r or q!"<<endl;
	}
	cout<<"quitting menu..."<<endl;

	return 0;
}


YourPets1.cpp

#include <iostream>
using namespace std;

int dog,cat,bird,fish;

void f(int pet)
{
	cout<<"pet id number:"<<pet<<endl;
}

int main()
{
	int i,j,k;
}


YourPet2.cpp

#include <iostream>
using namespace std;

int dog,cat,bird,fish;

void f(int pet)
{
	cout<<"pet id number:"<<pet<<endl;
}

int main()
{
	int i,j,k;
	cout<<"f():"<<(long)&f<<endl;
	cout<<"dog:"<<(long)&dog<<endl;
	cout<<"cat:"<<(long)&cat<<endl;
	cout<<"bird:"<<(long)&bird<<endl;
	cout<<"fish:"<<(long)&fish<<endl;
	cout<<"i:"<<(long)&i<<endl;
	cout<<"j:"<<(long)&j<<endl;
	cout<<"k:"<<(long)&k<<endl;

	return 0;
} 


Static.cpp

#include <iostream>
using namespace std;

void func()
{
	static int i = 0;
	cout<<"i = "<<++i<<endl;
}

int main()
{
	for(int x = 0;x < 10;x++)
	{
		func();
	}

	return 0;
}


FileStatic.cpp

#include <iostream>
using namespace std;

static int fs;

int main()
{
	fs = 1;
}


FileStatic2.cpp

#include <iostream>
using namespace std;

extern int fs;

int main()
{
	fs = 100;
}


Boolean.cpp

#include <iostream>
using namespace std;

int main()
{
	int i,j;
	cout<<"Enter an integer:";
	cin>>i;
	cout<<"Enter another integer:";
	cin>>j;
	cout<<"i<j is"<<(i<j)<<endl;
	cout<<"i>=j is"<<(i>=j)<<endl;
	cout<<"i<=j is"<<(i<=j)<<endl;
	cout<<"i==j is"<<(i==j)<<endl;
	cout<<"i!=j is"<<(i!=j)<<endl;
	cout<<"i&&j is"<<(i&&j)<<endl;
	cout<<"i||j is"<<(i||j)<<endl;
	cout<<"(i<10)&&(j<10) is"<<((i<10)&&(j<10))<<endl;

	return 0;
}


Bitwise.cpp

#include <iostream>
using namespace std;

#define PR(STR,EXPR) \
	cout<<STR; printBinary(EXPR); cout<<endl;

int main()
{
	unsigned int getval;
	unsigned char a,b;
	cout<<"Enter a number between 0 and 255:"<<endl;
	cin>>getval;
	a = getval;
	PR("a in binary:",a);
	cout<<"Enter a number between 0 and 255:"<<endl;
	cin>>getval;
	b = getval;
	PR("b in binary:",b);
	PR("a | b = ",a|b);
	PR("a & b = ",a&b);
	PR("a ^ b = ",a^b);
	PR("~a = ",~a);
	PR("~b = ",~b);
	unsigned char c = 0x5A;
	PR("c in binary: ",c);
	a |= c;
	PR("a |= c ;a =  ",a);
	b &= c;
	PR("b &= c ;b =  ",b);
	b ^= a;
	PR("b ^= a ;b =  ",b);

	return 0;
}

Rotation.cpp
#include <iostream>
using namespace std;

unsigned char rol(unsigned char val)
{
	int highbit;
	if(val & 0x80)
	{
		highbit = 1;
	}
	else
	{
		highbit = 0;
	}
	val<<=1;
	val |= highbit;

	return val;
}


unsigned char ror(unsigned char val)
{
	int lowbit;
	if(val & 1)
	{
		lowbit = 1;
	}
	else
	{
		lowbit = 0;
	}
	val>>=1;
	val |= (lowbit<<7);

	return val;
}


Union.cpp

#include <iostream>
using namespace std;

union Packed
{
	char i;
	short j;
	int k;
	long l;
	float f;
	double d;
};

int main()
{
	cout<<"aizeof(Packed) = "
		<<sizeof(Packed)<<endl;
	Packed x;
	x.i = 'c';
	cout<<x.i<<endl;
	x.d = 3.14159;
	cout<<x.d<<endl;

	return 0;
}


StructArray.cpp

#include <iostream>
using namespace std;

typedef struct
{
	int i,j,k;
}ThreeDpoint;

int main()
{
	ThreeDpoint p[10];
	for(int i = 0;i < 10;i++)
	{
		p[i].i = i+1;
		p[i].j = i+2;
		p[i].k = i+3;
	}

	return 0;
}


ArrayAddresses.cpp

#include <iostream>
using namespace std;

int main()
{
	int a[10];
	cout<<"sizeof(int) = "<<sizeof(int)<<endl;
	for(int i = 0;i < 10;i++)
	{
		cout<<"&a["<<i<<"]="<<(long)&a[i]<<endl;
	}

	return 0;
}


ArgsToInts.cpp

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char* argv[])
{
	for(int  i = 1;i < argc;i++)
	{
		cout<<atoi(argv[i])<<endl;
	}
}


PointerIncrement2.cpp

#include <iostream>
using namespace std;

typedef struct
{
	char c;
	short s;
	int i;
	long l;
	float f;
	double d;
	long double ld;
}Primitives;

int main()
{
	Primitives p[10];
	Primitives* pp = p;
	cout<<"sizeof(Primitives) = "
		<<sizeof(Primitives)<<endl;
	cout<<"pp = "<<(long)pp<<endl;
	pp++;
	cout<<"pp = "<<(long)pp<<endl;

	return 0;
}


PointerArithmetic.cpp

#include <iostream>
using namespace std;

#define P(EX) cout<<#EX<<":"<<EX<<endl;

int main()
{
	int a[10];
	for(int i = 0;i < 10;i++)
	{
		a[i] = i;
	}
	int* ip = a;
	P(*ip);
	P(*++ip);
	P(*(ip+5));
	int* ip2 = ip+5;
	P(*ip2);
	P(*(ip2-4));
	P(*--ip2);
	P(ip2-ip);

	return 0;
}


三.習題及答案


//: S03:Prototypes.h
//  Declares various functions
void f(int);
int g(float);
float h(char);
char k(void);  // same as char k()
///:~
//: S03:Prototypes.cpp {O}
// Implements functions declared in Prototypes.h
#include <iostream>
using namespace std;

void f(int i) {
  cout << "f(" << i << ") returning void\n";
}


int g(float x) {
  cout << "g(" << x << ") returning int\n";
  return 0;
}

float h(char c) {
  cout << "h(" << c << ") returning float\n";
  return 1.5;
}

char k(void) {   // same as char k()
  cout << "k() returning char\n";
  return 'a';
}

#include "Prototypes.h"

int main() {
  f(1);
  g(1.5);
  h('c');
  k();
}



方法一:

#include <iostream>
#include <cmath>    // for sqrt()
using namespace std;

int main() {
  const int MAX = 100;

  // Print 2 as a prime:
  cout << "2 ";

  for (int i = 3; i <= MAX; i += 2) 
  {
    float val = i; // Produce float value
    int mid = static_cast<int>(sqrt(val));
    int j;
    for (j = 3; j <= mid; j += 2)
	{
      if (i % j == 0)
	  {
        break;
	  }
	}
    if (j > mid)
	{
      cout << i << ' ';
	}
  }
  cout << endl;

  return 0;
}

方法二:
#include <iostream>
#include <cmath>    // for sqrt()
using namespace std;

#define MAX 100

int main() 
{
  cout<<"2";

  for (int i = 3; i < MAX+1; i+=2) 
  {
    for (int j = 3; j <= sqrt(i); j += 2)
	{
		if (i % j == 0)
		{
			break;
		}
	}
	if (j > sqrt(i))
	{
		cout << i << ' ';
	}

  }
  cout << endl;

  return 0;
}


#include <iostream>
#include <string>
#include <cstdio>

int main() {
    using namespace std;

    string word;
    for (;;) {
        int code;
        cin >> word;
        if (word == "exit" | word == "return")
            break;

        // Map words:
        if (word == "a" || word == "an" || word == "the")
            code = 0;
        else if (word == "after" || word == "before" ||
                 word == "beside" || word == "by" ||
                 word == "for" || word == "from" ||
                 word == "in" || word == "into" ||
                 word == "of" || word == "to")
            code = 1;
        else if (word == "if" || word == "else")
            code = 2;
        else if (word == "who" || word == "what" ||
                 word == "when" || word == "where" ||
                 word == "why")
            code = 3;
        else
            code = 4;

        // Print code description:
        switch (code) {
        case 0:
            puts("article");
            break;
        case 1:
            puts("preposition");
            break;
        case 2:
            puts("conditional");
            break;
        case 3:
            puts ("interrogative");
            break;
        default:
            puts("unmapped word");
            break;
        }
    }
    return 0;
} 



#include <iostream>
using namespace std;

int main()
{
	char c;
	while(true)
	{
		cout<<"MAIN MENU:"<<endl;
		cout<<"l:left,r:right,q:quit->";
		cin>>c;
		switch(c)
		{
		case 'q':
			{
			break;
			}
		case 'l':
			{
				cout<<"LEFT MENU:"<<endl;
				cout<<"select a or b:";
				cin>>c;
				switch(c)
				{
				case 'a':
					{
					cout<<"you choose 'a'"<<endl;
					continue;
					}
				case 'b':
					{
						cout<<"you choose 'b'"<<endl;
						continue;
					}
				default:
					
					{
						cout<<"you don't choose a or b"<<endl;
						continue;
					}
				}
			}
		case 'r':
			{
				cout<<"RIGHT MENU:"<<endl;
				cout<<"select c or d:";
				cin>>c;
				switch(c)
				{
				case 'c':
					{
						cout<<"you choose 'c'"<<endl;
						continue;
					}
				case'd':
					{
						cout<<"you choose 'd'"<<endl;
						continue;
					}
				default:
					{
						cout<<"you don't choose c or d"<<endl;
						continue;
					}
				}
			}
		}
		cout<<"you must type l or r or q!"<<endl;
	}
	cout<<"quitting menu..."<<endl;

	return 0;
}



#include <iostream>
using namespace std;

int main()
{
	int X=1,Y=2,Z=3;
	cout<<"A = "<<X+Y-2/2+Z<<endl;
	cout<<"A = "<<X+(Y-2)/(2+Z)<<endl;
	return 0;
}



#include <iostream>
using namespace std;

int dog;
char cat;
float bird;
double fish;

void f(int pet)
{
	cout<<"pet id number:"<<pet<<endl;
}

int main()
{
	int i,j,k;
	cout<<"f():"<<(long)&f<<endl;
	cout<<"dog:"<<(long)&dog<<endl;
	cout<<"cat:"<<(long)&cat<<endl;
	cout<<"bird:"<<(long)&bird<<endl;
	cout<<"fish:"<<(long)&fish<<endl;
	cout<<"i:"<<(long)&i<<endl;
	cout<<"j:"<<(long)&j<<endl;
	cout<<"k:"<<(long)&k<<endl;

	return 0;
} 

結果表示: