C++中有关拷贝构造函数的有关问题
C++中有关拷贝构造函数的问题
#include <iostream>
using namespace std;
class A
{
private:
int a;
public:
A()
{
a=0;
cout << "A's default constructor called.\n";
}
A(int i)
{
a = i;
cout <<"A's constructor called.\n";
}
void print()
{
cout << a <<",";
}
~A()
{
cout << "A's destructor called.\n";
}
int Geta()
{
return a;
}
};
class B:public A
{
public:
B()
{
b = 0;
cout << "B's default constructor called.\n";
}
B(int i, int j, int k):A(i),aa(j)
{
b = k;
cout << "B's constructor called.\n";
}
void print();
~B()
{
cout << "B's destructor called.\n";
}
private:
int b;
A aa;
};
void B::print()
{
A::print();
cout <<b<<","<<aa.Geta() <<endl;
}
int main()
{
B bb[2] = {B(10,15,20),B(1,2,3)};
for(int i = 0; i < 2; i++)
bb[i].print();
return 0;
}
析构时不理解,为什么只析构了bb[1],bb[2]。B(10,15,20),B(1,2,3)两个临时对象不用析构吗?
------解决思路----------------------
楼主,你这种写法叫做赋值构造,不是拷贝构造。
这样写的话,才是拷贝构造。
------解决思路----------------------
拷贝构造函数B (B &b) ;
拷贝赋值函数B &operator= (B &b) ;
B a ;
B b (a) ;或B b = a ;调用拷贝构造函数
B b ; b = a ;调用默认构造函数,然后调用拷贝赋值函数
简单理解就是,构建实例时调用构造函数,对实例进行变更调用赋值函数
而是否产生临时实例,就看执行的情况
是只调用构造函数
还是调用构造函数,然后再调用拷贝赋值函数了
------解决思路----------------------
++
#include <iostream>
using namespace std;
class A
{
private:
int a;
public:
A()
{
a=0;
cout << "A's default constructor called.\n";
}
A(int i)
{
a = i;
cout <<"A's constructor called.\n";
}
void print()
{
cout << a <<",";
}
~A()
{
cout << "A's destructor called.\n";
}
int Geta()
{
return a;
}
};
class B:public A
{
public:
B()
{
b = 0;
cout << "B's default constructor called.\n";
}
B(int i, int j, int k):A(i),aa(j)
{
b = k;
cout << "B's constructor called.\n";
}
void print();
~B()
{
cout << "B's destructor called.\n";
}
private:
int b;
A aa;
};
void B::print()
{
A::print();
cout <<b<<","<<aa.Geta() <<endl;
}
int main()
{
B bb[2] = {B(10,15,20),B(1,2,3)};
for(int i = 0; i < 2; i++)
bb[i].print();
return 0;
}
析构时不理解,为什么只析构了bb[1],bb[2]。B(10,15,20),B(1,2,3)两个临时对象不用析构吗?
------解决思路----------------------
楼主,你这种写法叫做赋值构造,不是拷贝构造。
int main()
{
//B bb[2] = { B(10, 15, 20), B(1, 2, 3) };
B b1(10, 15, 20);
B b2(1, 2, 3);
B bb[2] = { b1, b2 };
for (int i = 0; i < 2; i++)
bb[i].print();
return 0;
}
这样写的话,才是拷贝构造。
------解决思路----------------------
拷贝构造函数B (B &b) ;
拷贝赋值函数B &operator= (B &b) ;
B a ;
B b (a) ;或B b = a ;调用拷贝构造函数
B b ; b = a ;调用默认构造函数,然后调用拷贝赋值函数
简单理解就是,构建实例时调用构造函数,对实例进行变更调用赋值函数
而是否产生临时实例,就看执行的情况
是只调用构造函数
还是调用构造函数,然后再调用拷贝赋值函数了
------解决思路----------------------
++