一个类的成员可以有:另一个类的对象,类的自身指针,自身类对象的引用(私有的如何初始化呢,所以不行,换成静态的可以),自身类对象(构造时如何初始化呢?)
1 class A{ 2 public: 3 A(){} 4 A(A* a); 5 static A &reA; 6 private: 7 A *ptrA; 8 9 10 }; 11 A& A::reA = A();
考查*++p的运算: ++*p,先获得p指向的变量,再对这个变量自增,所以c变成了d
1 char arr[] = "abcdefghij",*p=arr; 2 p += 2; 3 cout << *p++ << endl;//输出c,形式*(p++)也是输出c 4 cout << p << endl;//输出defghij
char arr[] = "abcdefghij", *p = arr;
p += 2;
cout << (++*p) << endl; //输出d ,
cout << p << endl; //输出ddefghij
cout << arr << endl;
char arr[] = "abcdefghij",*p=arr; p += 1; cout << *++p << endl;//输出c cout << p << endl;//指向c
条件运算符里的求值顺序:运算符?:有三个操作数:在a?b:c中,操作数a首先被求值,根据a的值再求操作数b或c的值。
1 int i = 5; 2 int j = 0; 3 int k = 0; 4 k = (++i) > (j) ? (++i) : (j); 5 cout << k << endl; //输出7
free空指针,指针作为参数,也是传递的指针的值
会内存泄漏,程序不会崩溃
void foo(char *p) { p = (char*)malloc(100); strcpy(p, "hello"); } int main() { char *str = NULL; foo(str); if (!str) cout << "str is NULL" << endl; //结果为真 printf("%s", str); free(str); }
比较字符串用strcmp,函数依次比较字符的大小,依字典序,==比较的是两个字符指针是否指向同一地址;string可以和const char*比较
struct stu{ char name[10]; }; int main() { stu person[3] = { { "AA" }, { "AA" }, { "BB" } }; if (strcmp(person[1].name, "AA") == 0) cout << "strcmp is valid" << endl;//比较的是字符串的内容 if (person[1].name == "AA") cout << " 比较的是两个指针是否指向同一地址" << endl; string s1 = "abc"; string s2 = "abc"; cout << (s1 == "abc") << endl;// string类是可以用==和const char*比较的 char str1[] = "abc"; char str2[] = "abc"; const char str3[] = "abc"; const char str4[] = "abc"; const char* str5 = "abc"; const char* str6 = "abc"; cout << boolalpha << (str1 == str2) << endl; // 输出什么? cout << boolalpha << (str3 == str4) << endl; // 输出什么? cout << boolalpha << (str5 == str6) << endl; // 输出什么? }
返回字符数组指针和字符指针: 数组名不能自增,作为地址,是常量,不是左值
1 char *foo() 2 { 3 char *p = "hhd"; //返回p输出正常 4 char q[] = "jjj";//返回q输出未知 5 return q; 6 } 7 int main() 8 { 9 char *p = foo(); 10 cout << p << endl;
时间: 2024-10-08 20:18:19