//
// A.h
// Memory
//
// Created by xiangchenyu on 13-3-10.
// Copyright (c) 2013年 xiangchenyu. All rights reserved.
//
#ifndef Memory_A_h
#define Memory_A_h
class A
{
public:
A(int size):size(0),pStr(0)
{
this->size = size;
this->pStr = new int(size);
}
~A()
{
if(this->pStr)
delete []pStr;
}
void setValue(int index,const int& value)
{
if(index<this->size)
pStr[index] = value;
}
int getValue(int index) const
{
if(index<this->size)
return pStr[index];
else
return int();
}
public:
//拷贝构造函数
A(const A& a):size(a.size),pStr(0)
{
if(pStr)
{
delete []pStr;
pStr = NULL;
}
if (size)
{
pStr = new int[size];
for (int i = 0; i <size; ++i)
{
setValue(i,a.getValue(i));
}
}
}
//赋值函数
const A& operator=(const A& a)
{
if(this == &a)
return *this;
this->size = a.size;
if(pStr)
{
delete []pStr;
pStr = NULL;
}
if (size)
{
pStr = new int[size];
for (int i = 0; i <size; ++i)
{
setValue(i,a.getValue(i));
}
}
return *this;
};
private:
int size;
int* pStr;
};
#endif
调用的时候:
A a(10);
a.setValue(0, 555);
A a1 = a;
NSLog(@"a1-->%d",a1.getValue(0));
输出结果:555
C++的指针成员如果没有NEW,后果不看设想,如下所示
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->class Table{
Name * p;
size_t sz;
publish:
Table(size_t s = 15){p = new Name[sz=s];}
~Table(){delete[]p ;}
......
}
void h()
{
Table t1;
Table t2 = t1;
Table t3;
t3 = t2;
}
在h()结束时,默认构造函数调用了2次,而析构函数被调用了3次,为何?
Tablet1; 调用1次默认构造函数
Tablet2=t1;默认的对象的赋值操作,按成员赋值,其中关于指针p,仅仅是将t1.p赋值给t2.p,即t2.p = t1.p,并无内存分配。对象t1和t2的p指针均指向同一块内存。
Tablet3; 调用1次默认构造函数
t3=t2;原t3.p指针被t2.p覆盖,此时t3.p同样指向对象t1和t2的p指针的同一块内存。注意:t3原分配给p的内存由于没有指针指向,无法利用,造成存储浪费。
h()结束,对象t1,t2,t3的析构函数调用,此时对t1,t2,t3的指针p所指的同一块存储进行了三次删除,非常危险,导致的结果是无发预料的,很可能灾难性的。
因此明确定义类的复制构造函数(拷贝构造函数)和赋值预算可避免这样的错误。