钱能《C++程序设计教程》14章练习

当时学习敲的


[size=x-large][b]14.3[/b][/size]
这题还真带出问题来:临时对象的返回、参数对象自我保护的const机制。
原书的拷贝函数是没带const的,X::X(X& x) => X::X(const X& x)。
引用是很好的东西,要好好保护它,故聘请保镖const。
const还能与非const重载的……


#include <iostream>
using namespace std;

class X
{
protected:
int y;

public:
X(int);
X::X(const X&); // 原来的 X::X(X&);
~X();
};

X::X(int y)
{
cout << "构造:" << y << endl;
this->y = y;
}

X::X(const X& x) // 原来的 X::X(X& x)
{
cout << "拷贝:" << this->y << endl;
}

X::~X()
{
cout << "析构:" << this->y << endl;
}

X fx(X x) // 这里隐藏了拷贝函数的调用,返回临时对象时,会调用拷贝函数
{ // 而且参数会自我保护,提升为const
return x; // 关于临时对象,钱能书:14.7节 P323
}

int main(int argc, char *argv[])
{
// X a(1);
// X b = a;
a = fx( X(2) );
return 0;
}



[size=x-large][b]14.2[/b][/size]
对拷贝函数,并不用那么在意,其实就是堆上的数据一共有几份。

#include <iostream>
using namespace std;

class Vector
{
protected:
int size;
int* buffer;

public:
Vector(int s = 100);
Vector::Vector(Vector& v);
~Vector();

int& Elem(int ndx);
void Display();
void Set();
};

Vector::Vector(int s)  // 所谓的拷贝函数
{
size = s;
buffer = new int[size];
for (int i = 0; i < size; i++)
{
buffer[i] = i*i;
}
}

Vector::Vector(Vector& v)
{
size = v.size;
buffer = new int[size];
for (int i = 0; i < size; i++)
{
buffer[i] = i*i;
}
}

Vector::~Vector()
{
delete[]buffer;
}

int& Vector::Elem(int ndx)
{
if (ndx < 0 || ndx >= size)
{
cout << "error in index" << endl;
exit(1);
}
return buffer[ndx];
}

void Vector::Display()
{
for (int i = 0; i < size; i++)
{
cout << buffer[i] << endl;
}
}

void Vector::Set()
{
for (int i = 0; i < size; i++)
{
buffer[i] = i + 1;
}
}


int main(int argc, char *argv[])
{
Vector a(5);
a.Display();
cout << endl;

Vector b = a;
a.Set();
b.Display();

return 0;
}




[b][size=x-large]14.1[/size][/b]
此题我主要是想体会指针对象数组,与Java的稍有不同

#include <iostream>
using namespace std;
class Samp
{
protected:
int i;
int j;

public:
Samp()
{ cout << "Constructing:" << i << endl; }
~Samp()
{ cout << "Destroying:" << i << endl; }

public:
void Setij(int a, int b){i = a; j = b;}
int GetMulti(){return i*j;}
};


int main(int argc, char *argv[])
{
Samp* p = NULL;
p = new Samp[10];
// Samp[] p = new Samp[10]; // Java的做法

if (!p)
{
cout << "Allocation error!" << endl;
return -1;
}

for (int i = 0; i < 10; i++)
{
p[i].Setij(i, i);
}

for (int j = 0; j < 10; j++)
{
cout << "Multi[" << j << "]is:"
<< p[j].GetMulti() << endl;
}

delete[]p; // 忘了不就很危险~

cout << "Hello, world" << endl;
return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值