001:返回什么才好呢
这道题目考察this指针的使用,以及默认赋值函数
#include <iostream>
using namespace std;
class A {
public:
int val;
A(int n):val(n) {}
A() :val(123) {};
A& GetObj() {
return *this;
}
};
int main()
{
int m, n;
A a;
cout << a.val << endl;
while (cin >> m >> n) {
a.GetObj() = m; // 赋值重载默认
cout << a.val << endl;
a.GetObj() = A(n); // 赋值重载默认
cout << a.val << endl;
}
return 0;
}
002:Big & Base 封闭类问题
考察组合这种设计方式,记得初始化的时候调用里面类的构造函数
#include <iostream>
#include <string>
using namespace std;
class Base {
public:
int k;
Base(int n) :k(n) { }
};
class Big
{
public:
int v;
Base b;
// 在此处补充你的代码
Big(int n) :v(n), b(n){}
};
int main()
{
int n;
while (cin >> n) {
Big a1(n);
Big a2 = a1;
cout << a1.v << "," << a1.b.k << endl;
cout << a2.v << "," << a2.b.k << endl;
}
}
003:编程填空:统计动物数量
考察继承,静态函数,多态,特别经典的题目
#include <iostream>
using namespace std;
// 在此处补充你的代码
class Animal {
public:
static int number;
Animal() {
number++;
}
virtual ~Animal() {
number--;
}
};
int Animal::number= 0;
class Dog:public Animal {
public:
static int number;
Dog() {
number++;
}
~Dog() {
number--;
}
};
int Dog::number = 0;
class Cat :public Animal {
public:
static int number;
Cat() {
number++;
}
~Cat() {
number--;
}
};
int Cat::number = 0;
void print() {
cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}
int main() {
print();
Dog d1, d2;
Cat c1;
print();
Dog* d3 = new Dog();
Animal* c2 = new Cat;
Cat* c3 = new Cat;
print();
delete c3;
delete c2;
delete d3;
print();
}
004:这个指针哪来的
考察const关键字和this指针
#include <iostream>
using namespace std;
struct A
{
int v;
A(int vv) :v(vv) { }
// 在此处补充你的代码
const A* getPointer() const{
return this;
}
};
int main()
{
const A a(10);
const A* p = a.getPointer();
cout << p->v << endl;
return 0;
}