对象变作为成员变量时
只能由构造函数的初始化列表初始化
如果不显示去初始化成员对象,则系统默认添加无参构造方法。如果显示的调用构造函数,则调用函构造函数由形参列来匹配调用
student::student():s() –调用s的无参构造函数
student::student(int id,const char* name,int c=0,int e=0,int m=0):id(id),s(c,e,m)
#include<iostream>
#include<string.h>
using namespace std;
class score
{
public:score();
score(int,int,int);//注意不是int*,往空间放值
score(score&);
~score();
void show();
private:
int c;
int m;
int* net;
};
score::score():c(0),m(0)
{
this->net=new int;//默认构造也要分配空间
*(this->net)=0;
}
score::score(int c,int m,int n):c(c),m(m)
{
this->net=new int;
*(this->net)=n;
}
score::score(score& s)
{
*this=s;//浅拷贝,拷贝栈
this->net=new int;//深拷贝,拷贝堆
*(this->net)=*s.net;
}
score::~score()//不可重载,直接加功能就好
{
if(NULL!=this->net)
{
delete this->net;
this->net=NULL;
}
}
void score::show()
{
cout<<c<<" "<<m<<" "<<*net<<endl;
}
class student
{
public:student();
student(int,const char*,int,int,int);
student(student&);
// ~student(); 无指针类型,系统会释放
void show();
private:
int id;
char name[10];
score c;
};
student::student()/*:c()默认添加*/
{
name[0]='\0';
id=0;
}
//本类构造写的位置任意,子类构造也要写且只能写在列表上
student::student(int id,const char* name,int c,int m,int n):c(c,m,n)
{
this->id=id;
strcpy(this->name,name);
}
student::student(student& s):c(s.c)//!!提醒编译器要用自己写的重载构造
{ //而不是系统的浅拷贝
// *this=s; 内含指针,浅拷贝会出现重复释放的错误
this->id=s.id;
strcpy(this->name,s.name);
}
void student::show()
{
cout<<id<<" "<<name<<" ";
c.show();//不能接在cout后面,不能输出调用
}
int main()
{
student s1(1,"cmz",100,100,100);
student s2(s1);
s2.show();
}