C++_对象成员

对象成员

如果一个类的对象是另一个类的数据成员,则称这样的数据成员为对象成员。

class A
{
    //...
};
class B
{
    A a; //类A的对象a为类B的对象成员
public:
    //…
};

对象成员的初始化

使用对象成员着重要注意的问题是对象成员的初始化问题,即类B的构造函数如何定义?

例如有以下的类:

class X{
    类名1 对象成员名1;
    类名2 对象成员名2;
    …
    类名n 对象成员名n;
};

一般来说,类X的构造函数的定义形式为

X::X(形参表0):对象成员名1(形参表1),…,对象成员名i(形参表i) ,…,对象成员名n(形参表n)
{
    // …构造函数体
}
【例3.26】 对象成员的初始化
#include<iostream.h>
class A{
public:
    A(int x1, float y1)
    { x=x1; y=y1; }
    void show()
    { cout<<"\n x="<<x<<" y="<<y; }
private:
    int x;
    float y;
};
class B{
public:
    B(int x1,float y1,int z1):a(x1,y1)
    { z=z1; }
    void show()
    {
        a.show();
        cout<<" z="<<z;
    }
private:
    A a;
    int z;
};
main()
{
    B b(11,22,33);
    b.show();
    return 0;
}

具有对象成员的类构造函数的另一种定义

B(A a1, int z1):a(a1)
{ z=z1; }
main()
{
    A a(11,22);
    B b(a,33);
    b.show();
    return 0;
}
【例3.27】 对象成员的应用
#include<iostream.h>
#include<string.h>
class Score{
public:
    Score(float c,float e,float m);
    Score();
    void show();
    void modify(float c,float e,float m);
private:
    float computer;
    float english;
    float mathematics;
};
Score∷Score(float c,float e,float m)
{
    computer = c;
    english = e;
    mathematics = m;
}
Score∷Score()
{ computer=english=mathematics=0; }
void Score∷modify(float c,float e,float m)
{
    computer = c;
    english = e;
    mathematics = m;
}
void Score∷show()
{
    cout<<"\n Score computer: "<<computer;
    cout<<"\n Score english: "<<english;
    cout<<"\n Score mathematics: "<<mathematics;
}
class Student{
private:
    char *name; // 学生姓名
    char *stu_no; // 学生学号
    Score score1; // 学生成绩(对象成员,是类Score的对象)
public:
    Student(char *name1,char *stu_no1,float s1,float s2,float s3);
    ~Student(); // 析构函数
    void modify(char * name1,char *stu_no1,float s1,float s2,float s3);
    void show(); // 数据输出
};
Student∷Student(char *name1,char *stu_no1,float s1,float s2,float s3) :score1(s1,s2,s3)
{
    name=new char[strlen(name1)+1];
    strcpy(name,name1);
    stu_no=new char[strlen(stu_no1)+1];
    strcpy(stu_no,stu_no1);
}
Student∷~Student()
{
    delete []name;
    delete []stu_no;
}
void Student∷modify(char *name1,char *stu_no1,float s1,float s2,float s3)
{
    delete []name;
    name=new char[strlen(name1)+1];
    strcpy(name,name1);
    delete []stu_no;
    stu_no=new char[strlen(stu_no1)+1];
    strcpy(stu_no,stu_no1);
    score1.modify(s1,s2,s3);
}
void Student∷show()
{
    cout<<"\n name: "<<name;
    cout<<"\n stu_no: "<<stu_no;
    score1.show();
}
void main()
{
    Student stu1("Liming","990201",90,80,70);
    stu1.show();
    cout<<endl;
    stu1.modify("Zhanghao","990202",95,85,75);
    stu1.show();
}
name:Liming
stu_no:990201
Score computer: 90
Score english: 80
Score mathematics: 70
name:Zhanghao
stu_no:990202
Score computer: 95
Score english: 85
Score mathematics: 75
posted @ 2019-03-16 14:43  鲸90830  阅读(1173)  评论(0编辑  收藏  举报