嵌入式学习19(类的嵌套实现)

本文详细介绍了C++中如何使用构造函数初始化成员对象,包括默认构造、带参数构造及拷贝构造的不同实现方式,并通过具体示例代码演示了整个过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对象变作为成员变量时
只能由构造函数的初始化列表初始化
如果不显示去初始化成员对象,则系统默认添加无参构造方法。如果显示的调用构造函数,则调用函构造函数由形参列来匹配调用
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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值