面向对象编程之成员函数

1.  成员函数

1)  类内实现成员函数——inline函数

//示例

#include<iostream> 
  
usingnamespace std; 
  
classTest 
{ 
public: 
intx_; 
inlinevoid setX(int x) 
{ 
x_= x; 
} 
inlinevoid setY(int y) 
{ 
y_= y; 
} 
inlinevoid setZ(int z) 
{ 
z_= z; 
} 
inlineint getX() 
{ 
returnx_; 
} 
inlineint getY() 
{ 
returny_; 
} 
inlineint getZ() 
{ 
returnz_; 
} 
protected: 
inty_; 
private: 
intz_; 
}; 
  
intmain() 
{ 
Testt; 
t.x_= 5; 
t.setY(6);
t.setZ(7);
 
cout<< "t.x: " << t.x_ << endl; 
cout<< "t.y: " << t.getY() << endl; 
cout<< "t.z: " << t.getZ() << endl; 
return0; 
}

2)  类外实现成员函数

示例:

[main.cpp]
#include<iostream>
#include"Test.h"
 
usingnamespace std;
 
intmain()
{
    Test test;
 
    test.x_ = 5;
    //test.y_ = 6;//私有成员,类外不能访问
    //test.z_ = 7;//保护成员,类外不能访问
    test.init(4, 6, 7);
    test.display();
 
    return 0;
}
 
 
[Test.cpp]
#include"Test.h"
#include<iostream>
 
usingnamespace std;
 
voidTest::init(int x, int y, int z)
{
    x_ = x;
    y_ = y;
    z_ = z;
}
 
voidTest:: display()
{
    cout << "x_:" << x_<<endl;
    cout << "y_:" << y_<<endl;
    cout << "z_:" << z_<<endl;
}
[Test.h]
#ifndef_TEST_H_
#define_TEST_H_
 
classTest
{
    public:
        int x_;
 
void init(int x, int y, int z);
void display();
    private:
        int y_;
//int y_ =10;//该成员不能在类内初始化,只有静态常量整型数据成员才可以在类中初始化
    protected:
        int z_;
};
 
#endif

y_、z_是私有、保护成员,类外不可调用并且未初始化,所以是任意值


3)  成员函数的重载及默认参数

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值