C++纠错题 指针 和 形参实参问题
题目:
改正程序错误,使程序输出正常.
程序功能是打印Object类型变量的分量a
#include<iostream>
using namespace std;
struct Object {
int a;
int b;
};
Object& MyFunction(int a = 20, int b) {
// error 默认实参不在形参列表的结尾
Object* o = new Object;
o->a = a;
o->b = b;
return o;
// error 没有返回引用类型
}
int main() {
Object& MyFunction(int a = 20, int b);
// error 默认实参不在形参列表的结尾
Object& rMyObj = MyFunction(, 5);
// error 应输入表达式
cout << "rMyObj.a = " << rMyObj.a << endl;
delete rMyObj;
// 必须指向完整对象类型的指针
system("pause");
return 0;
}
改正:
#include<iostream>
using namespace std;
struct Object {
int a;
int b;
};
Object& MyFunction(int a, int b) {
Object* o = new Object;
o->a = a;
o->b = b;
return *o;
}
int main() {
Object& MyFunction(int a , int b);
Object& rMyObj = MyFunction(20, 5);
cout << "rMyObj.a = " << rMyObj.a << endl;
delete &rMyObj;
system("pause");
return 0;
}
- 这些错误都是visual 提示的,但是没有理解深刻意思,有没有人能解释一下 特别是这个 *a 和 &rMyObj