第三周 类和对象提高 - PKU[课程作业]程序设计与算法（三）C++面向对象程序设计

1:返回什么才好呢
#include <iostream>
using namespace std;
class A {
public:
int val;

A(int n = 123)
{
val = n;
}
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;
}

2: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):b(n) { v = 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;
}
}

3:编程填空：统计动物数量
/* 见：静态成员示例，继承和多态 */
#include <iostream>
using namespace std;

class Animal{
protected:
static int number;
public:
Animal() {}
virtual ~Animal() {}
friend void print();
};
int Animal::number = 0;

class Dog: public Animal{
private:
static int number;
public:
Dog() {
Animal::number++;
number++;
}
~Dog() {
Animal::number--;
number--;
}
friend void print();
};
int Dog::number = 0;

class Cat: public Animal{
private:
static int number;
public:
Cat() {
Animal::number++;
number++;
}
~Cat() {
Animal::number--;
number--;
}
friend void print();
};
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();
}

4:这个指针哪来的
#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;
}

5:魔兽世界之一：备战

https://blog.csdn.net/MoMo_flamboyant/article/details/79955977

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120