Question (16): Run the following C ++ code. What is the output?
class A{public: virtual void Fun(int number = 10) { std::cout << "A::Fun with number " << number; }}; class B: public A{public: virtual void Fun(int number = 20) { std::cout << "B::Fun with number " << number; }}; int main(){ B b; A &a = b; a.Fun();}
Thought; at first glance, we can see that this question is basically, although a is a reference of Class A, it actually refers to Class B. Here a. Fun () is a virtual function that uses the virtual function pointer to find the fun function in the virtual function table.
So output B: Fun with number is okay, but as for the form parameters in the function, I won't be sure.
The analysis in the Haitao log is very thorough, and the output should be 10
Why are you, Tao said, because the default parameter is actually processed during compilation, a A is a class during compilation, but during running, the virtual function dynamically points to the fun function of Class B, however, the value of number is 10.
Therefore
B::Fun with number 10
Run the following C code. What is the output?
char* GetString1(){ char p[] = "Hello World"; return p;} char* GetString2(){ char *p = "Hello World"; return p;} int _tmain(int argc, _TCHAR* argv[]){ printf("GetString1 returns: %s. \n", GetString1()); printf("GetString2 returns: %s. \n", GetString2()); return 0;}
Array P [] is the local variable of the function. Exit the function space and recycle it immediately.
* P is a String constant stored in the constant data area, which is global.
So getstring1 returns: a string of garbled characters
Getstring2 returns: Hello World
Question (19): The C code is running. What is the output?
int _tmain(int argc, _TCHAR* argv[]){ char str1[] = "hello world"; char str2[] = "hello world"; char* str3 = "hello world"; char* str4 = "hello world"; if(str1 == str2) printf("str1 and str2 are same.\n"); else printf("str1 and str2 are not same.\n"); if(str3 == str4) printf("str3 and str4 are same.\n"); else printf("str3 and str4 are not same.\n"); return 0;}
Str1 and str2 are arrays to allocate storage space for them. Of course, the addresses are different.
"Hello world" is a String constant and is stored in the constant data area. Of course, * str3 is the same as the address pointed to by * str4. It has only one copy in the memory.