C++ 类的使用:定义Person类 包含成员函数int max(int a,int b) ;用来返回a、b中最大值。定义成员变量 int age ,string name.

定义一个p.cpp文件,在该文件中定义Person类 包含成员函数int max(int a,int b) ;用来返回a、b中最大值。
定义成员变量 int age ,string name. 在main函数中调用该类的max函数输出最大值。

类似于Java,C++对于类的定义同样使用class关键字,注意在该类的大括号{}后面有一个分号 ;

#include <iostream>

using namespace std;

class Person{
    public:
    int max(int a,int b);
    int age;
    string name;
};

int Person::max(int a, int b){//类外实现Person类的max成员函数。
    int t = (a>b) ? a : b;
    return t;
}

int main(int argc, const char * argv[]) {
    Person p;//创建类的对象
    int max = p.max(8, 6);//通过类的对象调用该类的成员函数。
    cout<<"最大值为:"<<max<<endl;
    return 0;
}

输出结果:

有人或许会问,必须要类外实现成员函数吗,那肯定不是的啊,也可以在定义类的时候直接实现成员函数的功能,代码展示如下:

#include <iostream>

using namespace std;

class Person{
    public:
    int max(int a,int b){  //在类中实现成员函数功能
        int t = (a>b) ? a : b;
        return t;
    };
    int age;
    string name;
};

int main(int argc, const char * argv[]) {
    Person p;
    int max = p.max(8, 6);
    cout<<"最大值为:"<<max<<endl;
    return 0;
}

类外实现成员函数的功能看起来更方便简单,类内实现比较适合代码量较少的时候进行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱睡觉的小馨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值