1:返回什么才好呢
答案:
#include <iostream>
using namespace std;
class A {
public:
int val;
A(int
i){
//有参构造函数
val=i;
}
A(){
//无参构造函数
val=123;
}
A& GetObj(){
return *this; //这里返回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{
public:
static int number;
Animal(){
}
virtual ~Animal(){//这里用虚析够函数,为了让继承它的两个子类的析够函数起作用
}
};
int Animal::number = 0;
class Dog:public Animal{
public:
static int number;
Dog(){
Animal::number++;
number++;
}
~Dog(){
Animal::number--;
number--;
}
};
int Dog::number = 0;
class Cat:public Animal{
public:
static int number;
Cat(){
Animal::number++;
number++;
}
~Cat(){
Animal::number--;
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();
}
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;
}