跳至內容

用戶:Just44joy/c++程序設計原理與實踐

維基百科,自由的百科全書

學習總則

[編輯]
  • 紙上得來終覺淺,絕知此事要躬行。
  • 不放過任何一個看似簡單的題目。
  • 一段時間內,專心做一件事。

隨想感悟

[編輯]
  • from simple to complex 從最簡單易懂的輸入狀況出發,在最簡單的輸入情況下測試通過,然後測試複雜輸入,若出錯,則進一步分析和修改程序,再測試,如此反覆逐步深入,使得程序慢慢能夠處理一般的輸入條件。
  • 測試一定要考慮完備,無法完全完備則做到儘量完備,很多bug都是很隱秘的,不仔細做輸入測試很可能會被忽略,例如下面這個程序段。再一次證明了,真的不要忽視任何一個看似簡單的編程題目,其中玩玩隱藏着一些很容易忽視的細節,而這些是你不去動手就不可能發現的問題。
int main()
try {
    vector<int> numbers;
    int number;
    int numOfSum = 0;
    cin>>numOfSum;
    //cout<<"numOfSum: "<<numOfSum<<'\n';
    //cout << (unsigned) numOfSum << endl;
    while(cin>>number) {
        numbers.push_back(number);
    }
    //cout<<"numbers.size: "<<(int)numbers.size()<<'\n';
    //此处注意!!!:number.size()返回的是一个无符号整型,而numOfSum是整型,如果numOfSum被赋予一个负值,则结果很可能是true,产生意想不到的结果。
    if (numOfSum > numbers.size()) {
        cout<<"numOfSum > numbers.size()\n";
        error("The number of values you want to sum is bigger than the size of numbers");
    }
    int sum = 0;
    for (int i = 0; i < numOfSum; i++)
        sum += numbers[i];
    cout<<"The sum of the first "<<numOfSum<<" is: "<<sum<<'\n';
	return 0;
    }
    catch(exception &e){
        cerr<<"error: "<<e.what()<<'\n';
        return 1;
    }
  • 在基本完成,程序能夠處理一般的輸入條件後,對其做一個輸入條件完備的測試,爭取考慮到所有可能的輸入情況,以此增強程序的健壯性。
  • 一段程序,問:輸出什麼?
#include <iostream>
using namespace std;

struct CLS
{
	int m_i;
	CLS(int i) : m_i(i) {cout<<"that\n";cout<<m_i<<'\n'; }
	CLS()
	{
		CLS(0);
	}
	
};

int main(void)
{
	CLS obj;
	cout<<obj.m_i<<endl;
	return 0;
}
  • 思考:以下程序為什麼編譯出錯?
#include <iostream>
using namespace std;

struct S
{
	int a, b;
	S(int a_val) {a = a_val;}
	S(int aval, int bval)
	{
		S(aval);
		b = bval;
	}
};

int main(void)
{
	S obj(0, 1);
	cout<<"a: "<<obj.a<<" b: "<<obj.b<<endl;
	return 0;
}
  • 在C++中,一個類的構造函數沒法直接調用另一個構造函數,只是構建了一個臨時對象,並沒有調用另一個構造函數來初始化自己。正確的方法是使用placement new。[1]
  • 以下程序中,如何輸出p本身的值(p所指向的那個字符的地址),默認輸出p所指向的那個字符即字符'a'直至遇到一個結束符'\0'?
#include <iostream>

using namespace std;

int main()
{
	char *p = new char('a');
	cout<<p<<endl;

	return 0;
}

解答:將程序改為如下即可[2]

#include <iostream>

#include <iostream>

using namespace std;

int main()

{

char *p = new char('a');

cout<<static_cast<void *>(p)<<endl;

return 0;

}

chap1

[編輯]

chap2

[編輯]

chap3

[編輯]

chap4

[編輯]

chap5

[編輯]

chap6

[編輯]

chap7

[編輯]

參考資料

[編輯]

外部連結

[編輯]

PPP Support Website