单项选择题 · 试读样题 2/25
考点:虚函数动态绑定
【单选 02】 下列代码中,s1->draw(); 和 s2->draw(); 输出不同结果的主要原因是( )。
class Shape {
public:
virtual void draw() {
cout << "绘制图形" << endl;
}
virtual ~Shape() {}
};
class Circle : public Shape {
public:
void draw() override {
cout << "绘制圆形" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override {
cout << "绘制矩形" << endl;
}
};
int main() {
Shape* s1 = new Circle();
Shape* s2 = new Rectangle();
s1->draw();
s2->draw();
delete s1;
delete s2;
return 0;
}
-
A
draw() 是普通成员函数
-
B
Shape 中的 draw() 被声明为虚函数
-
C
Circle 和 Rectangle 中使用了 public 继承
-
D
指针变量名不同
单项选择题 · 试读样题 3/25
考点:类的 private 成员
【单选 03】 下面的代码在 main() 中有一行会导致编译错误,请找出来。
class Pet {
public:
Pet(string n, int a) : name(n), age(a) {}
string getName() { return name; }
void birthday() { age++; }
private:
string name;
int age;
};
int main() {
Pet cat("奶茶", 2);
cout << cat.getName(); // ①
cat.birthday(); // ②
cat.name = "大橘"; // ③
cout << cat.getName(); // ④
}
-
A
第 ① 行
-
B
第 ② 行
-
C
第 ③ 行
-
D
第 ④ 行