012:这个指针哪来的
题面
描述
填空,按要求输出
#include <iostream>
using namespace std;
struct A
{
int v;
A(int vv):v(vv) { }
// 在此处补充你的代码
};
int main()
{
const A a(10);
const A * p = a.getPointer();
cout << p->v << endl;
return 0;
}
思路
首先看到 a a a是 c o n s t A const\quad A constA类型,也就是常对象,因为其是常对象所以只能调用常函数,所以给 { } \{\} {}前加 c o n s t const const
其次因为 p p p是 c o n s t A ∗ const\quad A* constA∗指向常量的指针,所以只能指向常量,则 a . g e t P o i n t e r a.getPointer a.getPointer返回的一定是 c o n s t A ∗ const\quad A* constA∗
#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;
}