C++类与对象学习笔记(二)

一、内联成员函数

内联函数能够提升运行效率;使程序的体积会增大,以空间换时间;一般比较短小

原理:编译的时候将代码直接嵌入到调用的地方,从而减少了函数调用的开销;

内联函数仅仅只是给编译器一个提示而已,如果函数中有switch for,编译器不会以内联函数来解析;

#ifndef _TEST_H_
#define _TEST_H_

class Test
{
public:
    int Add(int a,int b);    //内联函数第一种形式
    int Add2(int a,int b)    //内联函数第二种形式(编译器会根据代码长度自动控制是否为内联函数)
    {
        return a+b;
    }

}

#endif //_TEST_H_

inline int Test::Add(int a,int b)
{
    return a+b;    
}

#include<iostream>

int main(void)
{
    
}

二、成员函数的重载及其缺省参数

相同的作用域

#ifndef _TEST_H_
#define _TEST_H_

class Test
{
public:
    int Add(int a,int b)  
    {
        return a+b;
    }
    
    void Init();
    void Init(int x);
    void Init(int x,int y);
    void Init(int x,int y,int z);//与下面注释的函数同时使用的时候会产生二义性

    //等价于void Init(int x=0,int y=0,int z=0);

    void Display();
private:
    int x_;
    int y_;
    int z_;
}

#endif //_TEST_H_

void Test::Init(){
    x_ = 0;
    y_ = 0;
    z_ = 0;
}

void Test::Init(int x){
    x_ = x;
    y_ = 0;
    z_ = 0;
}

void Test::Init(int x,int y){
    x_ = x;
    y_ = y;
    z_ = 0;
}

void Test::Init(int x,int y,int z){//与下面注释的函数同时使用的时候会产生二义性
    x_ = x;
    y_ = y;
    z_ = z;
}

//void Test::Init(int x/*=0*/,int y/*=0*/,int z/*=0*/){
//    x_ = x;
//    y_ = y;
//    z_ = z;
//}

void Test::Display(){
  cout << "x="<<x_<<" y=" <<y_<<" z=" << z_<<endl;
}

#include<iostream>

int main(void)
{
    Test t;
    t.Init();
    t.Display();    //x=0 y=0 z=0

    t.Init(10);     //x=10 y=0 z=0
    t.Display();

    return 0;
}

三、类与结构体

class与结构体的区别;在未指定访问权限的时的成员变量,class默认的时私有的,struct默认是公有的;

#include<iostream>
using namespace std;

struct Test2
{
    int x_;
    int y_;
    int z_;
    void Init(int x,int y,int z)
    {
        x_ = x;
        y_ = y;
        z_ = z;
    }
    void Display()
    {
        count<<"x="<<x_<<" y="<<y_<<"z="<<z_<<endl;
    }
}

Class Test3
{
//public:
    int x_;
    int y_;
    int z_;
    void Init(int x,int y,int z)
    {
        x_ = x;
        y_ = y;
        z_ = z;
    }
    void Display()
    {
        count<<"x="<<x_<<" y="<<y_<<"z="<<z_<<endl;
    }
}

int main(void)
{
    Test2 t;
    t.Init(10,20,30);
    //Test2 t2 =(10,20,30) ;    该方式初始化也可以;
    t.Display();

   
    Test3 t3;
    //t3.Init(10,20,30);        未标明public的情况下不允许,标明Public可以
    //Test3 t3 =(10,20,30) ;    未标明public的情况下不允许,标明Public可以
    return 0;
}

四、隐含的this指针

成员函数有一个隐含的附加形参,即指向该对象的指针,整个隐含的形参叫做this的指针;

使用this指针保证了每个对象可以拥有不同的数据成员,但处理这些成员的代码可以被所有对象共享;

成员变量是每个类对象独自的。成员函数是每个类所有对象公有只读的;

成员函数都隐藏了自身指针的参数;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值