001:返回什么才好呢
描述
程序填空,使其按要求输出
#include <iostream>
using namespace std;
class A {
public:
int val;
A(int
};
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;
}
输入
多组数据,每组一行,是整数m和n
输出
先输出一行:
123
然后,对每组数据,输出两行,第一行是m,第二行是n
样例输入
2 3
4 5
样例输出
123
2
3
4
5
#include <iostream>
using namespace std;
class A {
public:
int val;
A(int x=123) {
val = x;
}
A &GetObj() {//这里注意是引用,不然返回的是个地址,参考下一个代码
return *this;//就是把a返回去了。。。
}
//二刷此题多写了个函数:
/*A& operator=(int x) {
val = x;
return *this;
}*/
//之所以不用写这个函数,是因为类型转换构造函数可以自动把m转换为A(m)
//参考笔记类型转换构造函数定义下方的代码
};
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;
}
3:好怪异的返回值
描述
填空,使得程序输出指定结果
#include <iostream>
using namespace std;
// 在此处补充你的代码
getElement(int * a, int i)
{
return a[i];
}
int main()
{
int a[] = {1,2,3};
getElement(a,1) = 10;
cout << a[1] ;
return 0;
}
输入
无
输出
10
#include <iostream>
using namespace std;
int &//非引用的函数返回值不能作为等号的左值使用
getElement(int * a, int i)
{
return a[i];
}
int main()
{
int a[] = {1,2,3};
getElement(a,1) = 10;//等号的左值
cout << a[1] ;
return 0;
}
004:这个指针哪来的
描述
填空,按要求输出
#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;
}
输入
无
输出
10
样例输入
无
样例输出
10
const的详解:https://www.cnblogs.com/azbane/p/7266747.html
#include <iostream>
using namespace std;
struct A
{
int v;
A(int vv) :v(vv) { }
void print() const{ //类在成员的函数说明后面可以加const的关键字,该则成员函数成为常量成员函数
cout << this->v<<endl; //和静态成员函数不同,常量成员函数可以使用指针
};
const A *getPointer() const{//const成员函数。a要调用常量成员函数所以后面有const
return this; //用const修饰函数的返回值。如果给以“指针传递”方式的函数返回值加const修饰,那么函数返回值(即指针)的内容不能被修改,该返回值只能被赋给加const修饰的同类型指针。
//例如函数const char * GetString(void);
//如下语句将出现编译错误: char*str = GetString();
//正确的用法是: const char *str = GetString();
}
};
int main()
{
const A a(10);
a.print();//常量对象上可以使用常量成员函数,不能用非常量成员函数
const A * p = a.getPointer();
cout << p->v << endl;
getchar();
return 0;
}