特别注意:
006奇怪的复制类
依旧是补充代码:
程序填空,使其输出9 22 5
#include <iostream>
using namespace std;
class Sample {
public:
int v;
//正确
Sample() {};//默认构造函数必须存在
Sample(int n) :v(n) { };
Sample(const Sample & x){
v = x.v + 2;
};
};
void PrintAndDouble(Sample o)//此时将b传入该函数时,调用的是复制构造参数,也就是b到o的过程中v变成了9
{
cout << o.v;
cout << endl;
}
int main()
{
Sample a(5);
Sample b = a;//此时调用复制函数
PrintAndDouble(b);
Sample c = 20;
PrintAndDouble(c);//将对象作为形参,调用复制构造函数
Sample d;
d = a;
cout << d.v;
return 0;
}
007返回什么才好
#include <iostream>
using namespace std;
class A {
public:
int val;
A() {
val = 123;
}
A(int x) {
val = x;
};
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;
}
008:超简单的复数类
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
double r, i;
public:
void Print() {
cout << r << "+" << i << "i" << endl;
}
Complex() {};
Complex(const char* p) {//该函数可理解为是将等号的东西作为一个参数传入函数
r = p[0] - '0';
i = p[2] - '0';
};
};
int main() {
Complex a;
a = "3+4i"; a.Print();
a = "5+6i"; a.Print();
return 0;
}
以下语句错误,是由于y重定义。
int fun(int x, int y) { int y=10; return x+y; }