1、
#include<iostream> using namespace std; class A { public: virtual void f() { cout<<"A::f()"<<endl; } void f() const { cout<<"A::f() const"<<endl; } }; class B: public A { public: void f() { cout<<"B::f()"<<endl; } void f() const { cout<<"B::f() const"<<endl; } }; void g(const A* a) { a->f(); } int main() { A* a = new B(); a->f(); g(a); delete a ; return 0; }
输出
B::f()
A::f() const
也就是说,常量对象会优先调用同名的常成员函数,非常量对象会优先调用同名的非常成员函数
2、
#include <iostream> using namespace std; int main() { char str1[] = "abc"; char str2[] = "abc"; const char str3[] = "abc"; const char str4[] = "abc"; const char* str5 = "abc"; const char* str6 = "abc"; cout << ( str1==str2 ) << endl; cout << boolalpha << ( str3==str4 ) << endl; cout << boolalpha << ( str5==str6 ) << endl; return 0; }
分别输出false,false,true。str1和str2都是字符数组,每个都有其自己的存储区,它们的值则是各存储区首地址,不等;str3和 str4同上,只是按const语义,它们所指向的数据区不能修改。str5和str6并非数组而是字符指针,并不分配存储区,其后的“abc”以常量形式存于静态数据区,而它们自己仅是指向该区首地址的指针,boolalpha 用符号形式表示真假。
3、不用sizeof输出int的字节数
#include <iostream.h> #include <string.h> void main(void) { int a[2]; int *a1 = &a[1]; int *a0 = &a[0]; cout << a1 - a0 << endl; //1 cout << (int)a1 - (int)a0 << endl; //32位机器输出4, 64位机器输出8 return; }