问题描述
- c++构造函数的问题,求大神赐教
-
#include
class A
{
public :
A()
{
a=0;
cout<<"A's default constructor called.n";
}
A(int i)
{
a=i;
cout<<"A's constructor called.n";
}
~A()
{
cout<<"A's destructor called.n";
}
void print()const
{
cout<<a<<",";
}
int Geta()
{
return a;
}
private :
int a;};
class B:public A
{
public :
B()
{
b=0;
cout<<"B's default constructor called.n";
}
B(int i,int j,int k);
~B()
{
cout<<"B's destructor called.n";
}
void print();
private:
int b;
A aa;
};B::B(int i,int j,int k):A(i),aa(j)
{
b=k;
cout<<"B's constructor called.n";
}void B::print()
{
A::print();
cout<<b<<","<<aa.Geta()<<endl;
}void main()
{
B bb;
bb=B(1,2,5);
bb.print();
}主要是main函数中这条语句不理解:bb=B(1,2,5). B(1,2,5)是什么意思?不应该是bb=B b1(1,2,5)吗?
解决方案
bb=B(1,2,5)
先调用B的构造函数,
然后调用缺省的赋值操作符赋值给bb
解决方案二:
B bb;
bb=B(1,2,5);
先构造一个临时的对象TEMP,然后将临时对象赋值给已存在对象bb
时间: 2024-10-23 05:37:43