课程:北京大学程序设计与算法(三) MOOC
OJ: OpenJudge
007:(010:)返回什么才好呢
由于主函数里面声明变量调用无参构造函数,且要求输出123,直接手写一个无参构造函数。
之后书写有参构造函数,这也比较容易。
最后时GetObj的编写,需要用到this指针,返回该对象的引用。
注意返回引用,而不是对象,因为后者会调用拷贝构造函数创建临时对象,m和n修改的不是对象a了。
完整代码如下:
#include <iostream>
using namespace std;
class A {
public:
int val;
A(int
al)
{
val = al;
}
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;
}
011:Big & Base 封闭类问题
这个题需要手写构造函数和复制构造函数。因为Big类里有Base对象,所以使用初始化列表。
而主函数里a1调用了构造函数,a2调用了复制构造函数,所以编写这两个函数即可。
构造函数中,将Big的成员变量用传入的参数赋值。
复制构造函数中,与上述类似,分别赋值。
完整代码如下:
#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){}
Big(const Big& big):v(big.v),b(big.b)
{
}
};
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;
}
}
012:这个指针哪来的
这个题需要我们编写getPointer函数。根据题意只需要用this指针返回当前对象地址即可。
注意this 是const A *类型的,返回值也需为这个类型。
而且p为常量指针,需要将这个函数设定为常量函数
完整代码如下:
#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;
}