面向对象:求最大值

C++:以面向对象的方式求几个数的最大值,程序中包含类的定义,对象的初始化,构造函数和析构函数

#include<iostream>
using namespace std;
class MyClass
{
private:
    int value;
public:
    MyClass(int i)  //构造函数
    {
        value=i;
        cout<<"Constructor called"<<endl;
    }

    int Max(int x,int y)   //求两个数的最大值
    {
        return x>y?x:y;
    }

    int Max(int x,int y,int z)   //求三个数的最大值
    {
        if(x>y)
            return x>z?x:z;
        else
            return y>z?y:z;
    }

    int GetValue() { return value;};
    ~MyClass() { cout<<"Destructor called"<<endl;}  //析构函数
};

int main()
{
    MyClass obj(10);
    cout<<"The value is:"<<obj.GetValue()<<endl;
    cout<<"Max number is:"<<obj.Max(10,20)<<endl;
    return 0;
}

运行结果:这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_37590253/article/details/67640414