3.2类的成员函数【C++】

1.成员函数的性质


返回值类型  函数名字  (函数参数)

{
      函数体;
}


他与普通函数的区别在于,

成员函数是属于某一个类的,是类的一个成员,

在类外调用类内的函数时要注意函数的访问属性,

成员函数可以访问类内的任何一个函数,

对于类内的成员函数,一般的做法是需要被外界调用的成员函数,声明为公用的,不需要被外界调用的成员函数声明为私用的,


2.在类外调用成员函数,将3.1中的studen类的成员函数改为类外定义的形式,

class student

{
public:
    void setin();
    void show();

private:
    string num,name,sex;
};

 void student::setin()
    {
        cout<<"Please enter student's num name sex"<<endl;
        cin>>num>>name>>sex;
    }

 void student::show()
    {
        cout<<"The studnt's information is :"<<endl;
        cout<<"num :"<<num<<endl<<"name :"<<name<<endl<<"sex :"<<endl;
    }


(1)在类外定义成员函数时,必须首先在类内写出成员函数的原型声明,然后在类外定义,这就要求类的声明,必须在成员函数定义之前,

(2)如果成员函数只有两三行,也可以在类内定义成员函数,


3 inline 成员函数

对于inline函数而言,在编译时,调用的代码直接嵌入到调用函数处。

4.成员函数的存储方式

* 分配内存空间时,系统只会为对象分配内存空间

类的对象占用内存空间的情况实验

class Test
{
private: char c;//定义 charc
public:
    void show();//调用函数


};
void Test::show()
{
    cout<<"Char in test is "<<c;//完成show函数
}
int _tmain(int argc, _TCHAR* argv[])
{
    Test test; //定义对象
    cout<<"The size of test is :"<<sizeof(test);
    system("pause");
    return 0;
}

相同类的不同对象执行相同成员函数,输出不同得结果

class Test
{
private: char c;//定义 char c
public:
    void show();//调用函数
    void set(char ch);

};
void Test::show()
{
    cout<<"Char in test is "<<c;//完成show函数
}
void Test::set(char ch)
{
    c=ch;
}
int _tmain(int argc, _TCHAR* argv[])
{
    Test test1; //定义对象
    Test test2;
    test1.set('a');
    test2.set('b');

    cout<<"The size of test is :"<<sizeof(test1)<<endl;
    cout<<"The size of test is :"<<sizeof(test2)<<endl;
    system("pause");
    return 0;
}



发布了36 篇原创文章 · 获赞 17 · 访问量 6274

猜你喜欢

转载自blog.csdn.net/qq_39248307/article/details/78115071