11A拷贝构造函数

2016-06-18  本文已影响4人  LuckTime

//======================================

//===========拷贝构造函数的重载=========
//======================================
//======================================
//======================================
两个指针成员指向默认拷贝构造函数,会出现地址错误。

include <iostream>

using namespace std;

class A{
int date;
public:
A(int d) :date(d){
cout << "A(int)"<< endl;
}

A(char d) :date(d){
cout << "A(char)"<< endl;
}
A(bool d) :date(d ? 123:345){
、cout << "A(bool)"<< endl;
}
A(int& d) :date(d){
cout << "A(int&)"<< endl;
}

A(const A& o) :date(o.date){
cout << "A(const &)"<< endl;
}
/* A(const A o) :date(o.date){
cout << "A(const &)"<< endl;
}
*///将引用去掉,这样行不行。。不行!为什么?引用是用来初始化变量的别名。传入的数据进行初始化,非引用会将实参复制一部分给形参,此时的形参是新变量,由实参进行初始化
//如果没有引用,A a2(a1),调用A(A o). A o (a1)..相当于反复的创建a1,因此不行。(创建对象时,要调用构造函数。调用构造函数时,又要创建形参,而形参是新的对象,而创建新对象有要调用构造函数,调用构造函数需要形参,这样反反复复编译器编译不能成功)
virtual ~A(){
cout <<"~A()" <<endl; //一个类中存在一个析构函数
}
void show()const {
cout << "date="<< date<<endl;
}

};

void show(A obj)
{
obj.show(); //拷贝构造函数的使用
}

void func(const A& obj)
{
obj.show(); //注意传入参数为常量,因此在类中的show函数中,需要定义为常量
}
int main(int argc,char argv[])
{
//A a1(3);
show('v'); //调用类外的show函数,并定义A obj为char 类型的字符串。。用过之后直接析构掉了。。
show(23);
A a1(3);
show(a1);
//A a2(true);
//A& a3 = a1;
//a3.show();
//show(a3);
//A a4(a1); //这个是采用A(const A& o )
//A a5('V');
//A a6();
cout <<"======func========" << endl;
func(a1); //因为使用引用,因此在已经有a1的情况下,不会再创建新对象
}

/*
//动态数组类,可变长短的数组。。

include <iostream>

include <string>

using namespace std;

class A{
char* p; //因为是动态数组,不能直接定义数组。
int len;

public:
A(int n) : len(0),p(NULL) { //构造函数,设置n个数组长度
resize(n);
}

void resize(int n){ //作用,将数组长度调整为指定长度
char* q = new char[n]; //新传入数组,设定长度
int min = ( n< len? n:len );
if(p!=NULL)
{
for(int i=0; i< min; i++)
{ //p指向的数据全部转移到q指向的空间
q[i] = p[i];
}
delete []p;
p = q;
for(i = min; i<n; i++)
p[i] = '\0';
}
len = n;
}
void set(int index,char value)
{
if(index>0)
p[index] = value;
}

char get(int index){
return p[index];
}

~A(){
if(p!=NULL){
delete[] p;
}
}
A (const A& o): len(o.len){
p = new char [len];
for(int i=0; i<len; i++)
p[i] = o.p[i];
} //拷贝构造函数,此算法是深拷贝
};

int main()
{
A a1(10);
a

}
//此方法是浅显的拷贝
*/

include <iostream>

using namespace std;

class Array{
char* p;
int len;

public:
Array(int n) : len(n),p(new char[n]){}
int size(){
return len;
}

~Array(){

delete []p;
}

void fill(char start,int skip)
{
for(int i = 0;i<len ;i++)
p[i]=start +i*skip;
}

void show(){
for(int i=0; i< len; i++ )
cout << p[i];
cout << endl;
}

Array(const Array& o) :len(o.len){
p = new char [len];
for(int i=0; i<len; i++)
p[i] = o.p[i];
}
};

int main()
{
Array a1(10);
a1.fill('a',1);
a1.show();
Array a2(a1);
a2.fill('A',1);
a2.show();
a1.show();
}

上一篇下一篇

猜你喜欢

热点阅读