C++:类的成员函数

本文通过三个示例展示了C++中类的成员函数的应用,包括直接赋值和使用成员函数设置及获取对象属性,以及计算体积的方法。示例详细解释了如何声明、定义和调用类的成员函数,以及如何通过成员函数来操作对象的状态。
摘要由CSDN通过智能技术生成

 

// 例1.类成员函数
/*
#include <iostream>
using namespace std;

class Box
{
public:
    double length;   // 长度
    double breadth;  // 宽度
    double height;   // 高度
};

int main()
{
    Box Box1;        // 声明 Box1,类型为 Box
    Box Box2;        // 声明 Box2,类型为 Box
    double volume = 0.0;     // 用于存储体积

    // box 1 详述
    Box1.height = 5.0;
    Box1.length = 6.0;
    Box1.breadth = 7.0;

    // box 2 详述
    Box2.height = 10.0;
    Box2.length = 12.0;
    Box2.breadth = 13.0;

    // box 1 的体积
    volume = Box1.height * Box1.length * Box1.breadth;
    cout << "Box1 的体积:" << volume << endl;

    // box 2 的体积
    volume = Box2.height * Box2.length * Box2.breadth;
    cout << "Box2 的体积:" << volume << endl;
    return 0;
}
*/

// 例2.类成员函数
/*
#include <iostream>
using namespace std;

class Box
{
public:
    double length;         // 长度
    double breadth;        // 宽度
    double height;         // 高度

    // 成员函数声明
    double getVolume(void);
    void setLength(double len);
    void setBreadth(double bre);
    void setHeight(double hei);
};

// 成员函数定义
double Box::getVolume(void)
{
    return length * breadth * height;
}

void Box::setLength(double len)
{
    length = len;
}

void Box::setBreadth(double bre)
{
    breadth = bre;
}

void Box::setHeight(double hei)
{
    height = hei;
}

// 程序的主函数
int main()
{
    Box Box1;                // 声明 Box1,类型为 Box
    Box Box2;                // 声明 Box2,类型为 Box
    double volume = 0.0;     // 用于存储体积

    // box 1 详述
    Box1.setLength(6.0);
    Box1.setBreadth(7.0);
    Box1.setHeight(5.0);

    // box 2 详述
    Box2.setLength(12.0);
    Box2.setBreadth(13.0);
    Box2.setHeight(10.0);

    // box 1 的体积
    volume = Box1.getVolume();
    cout << "Box1 的体积:" << volume << endl;

    // box 2 的体积
    volume = Box2.getVolume();
    cout << "Box2 的体积:" << volume << endl;
    return 0;
}
*/

// 手敲test 3.类成员函数
#include<iostream>
using namespace std;

class A
{
public:
    int a;
    int b;
    int c;
    int func();
};

int A::func()
{
    return a * b * c;
}

int main()
{
    A class_1;
    A class_2;
    class_1.a = 1;
    class_1.b = 2;
    class_1.c = 3;
    class_2.a = 4;
    class_2.b = 5;
    class_2.c = 6;
    cout << class_1.func() << endl;
    cout << class_2.func() << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值