C++之类成员函数

C++之类成员函数

#include <iostream>
#include <cstring>
#include <cstdlib>

using namespace std;

class Bird {
public:
    double l;
    double b;
    double w;
    double h;

    double get_volume();

    void set_value(double len, double breadth, double width, double height);
};

inline double Bird::get_volume() {
    return l * b * w * h;
}

inline void Bird::set_value(double len, double breadth, double width, double height) {
    l = len;
    b = breadth;
    w = width;
    h = height;
}

Bird bird;

int main() {
    system("chcp 65001");
    bird.set_value(10, 20, 30, 40);
    double volume = bird.get_volume();
    cout << "体积为:" << volume << endl;
    return 0;
}
输出:
Active code page: 65001
体积为:240000

在类内定义的函数就是成员函数,使用inline关键字修饰的就是内联函数,内联函数只有定义的时候才有效,在类内声明函数原型,在类外定义时使用inline修饰,若在函数原型前修饰,而在类外没有用inline修饰,则不是内联函数。
:: 叫作用域区分符,指明一个函数属于哪个类或一个数据属于哪个类。
:: 可以不跟类名,表示全局数据或全局函数(即非成员函数)。

#include <iostream>
#include <cstring>

using namespace std;

int year;
int month;
int day;

void set(int x, int y, int z) {
    ::year = x;
    ::month = y;
    ::day = z;
}

class Tdate {
public:
    //成员函数
    void set(int x, int y, int z) {
        //非成员函数(全局函数)
        ::set(x, y, z);
    }

private:
    int year;
    int month;
    int day;
};

Tdate t_date;

int main() {
    int x = 2021;
    int y = 7;
    int z = 20;
    t_date.set(x, y, z);
    cout << "year-month-day:" << year << "/" << month << "/" << day << endl;
    return 0;
}
输出:
year-month-day:2021/7/20
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值