C++——复习篇1

发布时间:2026/6/20 17:12:14

C++——复习篇1 1.编写程序判断一个变量是不是指针C编译器的匹配调用优先级重载函数函数模板变参函数#includeiostream #includestring #includetypeinfo using namespace std; void test(int i) { cout void test(int i) endl; } templatetypename T void test(T v) { cout void test(T v) endl; } void test(...) { //变参函数 ...表示可以接受任意多的参数 cout void test(...) endl; } int main() { int i 0; test(i); //void test(int i) return 0; }思路将变量分为两类指针vs非指针编写函数指针变量调用时返回true非指针变量调用时返回false#includeiostream #includestring #includetypeinfo using namespace std; class Test { public: Test() { } virtual ~Test() { } }; templatetypename T bool IsPtr(T* v) { //和指针匹配 return true; } bool IsPtr(...) { return false; } int main() { int i 0; int* p i; cout IsPtr(i) endl; //0 cout IsPtr(p) endl; //1 Test t1; Test* p1 t1; cout IsPtr(t1) endl; //0 cout IsPtr(p1) endl; //1 return 0; }缺陷变参函数无法解析对象参数可能造成程序崩溃所有如何让编译器精准匹配函数但不进行实际的调用#includeiostream #includestring #includetypeinfo using namespace std; class Test { public: Test() { } virtual ~Test() { } }; templatetypename T char IsPtr(T* v) { //和指针匹配 return d; } int IsPtr(...) { return 0; } #define ISPTR(p) (sizeof(IsPtr(p))sizeof(char)) int main() { int i 0; int* p i; cout ISPTR(i) endl; //0 cout ISPTR(p) endl; //1 Test t1; Test* p1 t1; cout ISPTR(t1) endl; //0 cout ISPTR(p1) endl; //1 return 0; }2.如果构造函数中抛出异常会发生什么情况构造函数中抛出异常会发生构造过程立即停止当前对象无法生成析构函数不会被调用对象所占用的空间立即收回#includeiostream #includestring #includetypeinfo using namespace std; class Test { public: Test() { cout Test() endl; throw 0; } virtual ~Test() { cout virtual ~Test() endl; } }; int main() { Test* p reinterpret_castTest*(1); try { p new Test(); } catch (...) { cout Exception... endl; } cout p p endl; //仍为最初给p指针赋值的值 return 0; }运行结果Test()Exception...p00000000000000013.try和catch的另一种用法1函数声明和定义时可以直接指定可能抛出的异常类型2异常声明成为函数的一部分可以提高代码可读性#includeiostream #includestring #includetypeinfo using namespace std; int func(int i, int j) throw(int) { if ((0 j) (j 10)) { return (i j); } else { throw 0; } } void test(int i) try { cout func(i,i) func(i, i) endl; } catch (int i) { cout Exception: i endl; } int main() { test(5); //func(i,i)10 test(10); //Exception: 0 return 0; }

相关新闻