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

1、函数原型必须在类(class)中定义。

2、函数体:

*可以在类中定义函数体

*也可以在外部定义.

3、this指针.

4、const放后面修饰成员函数。


# 一般会把比较短小的函数体放在类中,把比较长的函数的函数体放外部。

# 也可以把函数体都放在外部,这样看起来比较清晰。


Demo:

#include <iostream>
#include <string>
using namespace std;

/*类的成员函数*/

class SalesItem{

public:
        /// 外部成员函数,必须先声明
        void printAverage() const;

        /// 类的内部成员函数
        bool isSameItem(const SalesItem &rhs) const{
            //this:当前对象,this是指针
            return (this->isbn == rhs.isbn);
        }

public:
        std::string isbn;   //书号
        unsigned allSold;   //销量
        double revenue;     //收入
};

/// 外部成员函数,必须先声明
void SalesItem::printAverage() const
{
    //this->isbn = "0000";  const放后面修饰,不能修改。
    cout << "** 平均 **\n";
}


int main()
{
    SalesItem item1, item2;

    item1.isbn = "201-7852-16";
    item1.allSold = 10;
    item1.revenue = 300.00;

    item2.isbn = "201-7852-16";
    item2.allSold = 15;
    item2.revenue = 450.00;

    if (item1.isSameItem(item2)){
        cout << "这两个item是  一样的!\n";
    }else{
        cout << "这两个item是不一样的!\n";
    }

    item1.printAverage();

    return 0;
}
输出:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值