一、 阅读程序,写出结果
// 1、
#include <iostream>
using namespace std;
void fun1(char* s1, char* s2)
{
int i = 0;
for (; *s1 == *s2; s1++, s2++)
{
i++;
}
cout << s1 << endl;
cout << i << endl;
}
void fun2(char*& s1, char*& s2)
{
int i = 0;
for (; *s1 == *s2; s1++, s2++)
{
i++;
}
*(s1 - 1) = '\0';
*(s2 - 1) = '\0';
}
int main()
{
char string1[] = "I love Nanjing";
char string2[] = "I love Southeast University";
char* p1 = string1;
char* p2 = string2;
fun1(p1, p2);
fun2(p1, p2);
cout << p1 << endl;
cout << p2 << endl;
cout << string1 << endl;
cout << string2 << endl;
return 0;
}
考察知识点指针引用,字符串存储。
重难点解析:
1、可以使用字符数组或者字符指针去指向一个字符串,字符串在内存中实际按照字符数组的形式进行存储,形如"123"的字符串在内存中是长度为4的字符数组(末尾会自动增加字符串结束标志'\0')。字符串是字符数组,但字符数组不一定是字符串。如char str1[] = {'1', '2', '3'};只是字符数组而不是字符串。char str1[] = {'1', '2', '3', '\0'};和char* str1 = "123";才是等价的。
2、引用的本质是常指针(编译器内部实现)。
输出结果:
Nanjing
7
Nanjing
Southeast University
I love
I love
// 2、
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student() { num++; }
~Student() { num--; }
static int num;
private:
string name;
};
int Student::num = 0;
class Undergraduate: public Student
{
public:
Undergraduate(int i = 0, float s = 100)
{
id = i;
score = s;
num++;
}
~Undergraduate() { num--; }
static int num;
private:
int id;
float score;
};
int Undergraduate::num = 0;
class Postgraduate: public Student
{
public:
Postgraduate(string s = "UNDK", string n = "KDS")
{
sa = s;
na = n;
num++;
}
~Postgraduate() { num--; }
static int num;
private:
string sa, na;
};
int Postgraduate::num = 0;
int num = 100;
Undergraduate ug(1);
Postgraduate p;
int main()
{
int num = 0;
cout << num << endl;
cout << ::num << endl;
cout << ug.num << endl;
cout << p.num << endl;
cout << Student::num << endl;
{
Undergraduate u1;
Postgraduate p1;
cout << u1.num << endl;
cout << p1.num << endl;
cout << Student::num << endl;
}
Student* s = new Undergraduate;
cout << Undergraduate::num << endl;
cout << Student::num << endl;
delete s;
cout << Undergraduate::num << endl;
cout << Student::num << endl;
}
考察知识点类的静态成员变量,子类构造对象时子父类构造函数调用顺序,虚析构函数,new、delete操作符的默认行为,默认命名空间和作用域问题。
重难点解析:
1、子类在构造对象时首先会调用父类的构造函数再执行本类构造函数的函数体。
2、new一个对象会按照顺序调用对应类的构造函数对该对象进行初始化,delete一个通过new出来的对象指针会调用对应类的析构函数释放资源。
3、当父类的析构函数为非虚函数时,通过父类指针pF指向一个new出来的子类对象,然后delete pF;时采用的是静态编译,按照pF指针类型只会调用了父类的析构函数,不会按照多态首先调用子类的析构(释放子类自己特有的成员)再调用父类的析构(释放从父类继承的成员)。只有父类的析构函数是虚析构时才能按照多态正确地去析构父类指针指向new出来的子类对象。
输出结果:
0
100
1
1
2
2
2
4
2
3
2
2
就写到这里,想要了解更多东南大学553C++复试笔试真题请私信留言。