c++入门经典学习笔记之使用函数默认值

#include <iostream>
using namespace std;
   
class Rectangle
{
public:
    Rectangle(int width, int height);
    ~Rectangle(){}
  
 
    void drawShape(int width=13, int height=13) const; //mo ren zhi

    int func1()
    {
        return width;
    }

    int func2()
    {
        return height;
    }
   

private:
    int width;
    int height;
};
   
Rectangle::Rectangle(int newWidth, int newHeight)
{
    width = newWidth;
    height = newHeight;
}
   


   
void Rectangle::drawShape(int width, int height) const
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            std::cout << "*";
        }
        std::cout << "\n";
    }
}
  
int main()
{
    Rectangle box(30,5);
    cout<<"box.width= "<<box.func1()<<"\n"<<"box.height= "<<box.func2()<<endl;
    std::cout << "drawShape(): \n";   
    box.drawShape();                                //mo ren zhi
    std::cout << "\ndrawShape(40, 2): \n";
    box.drawShape(40, 2);                           //you liang ge canshu 
    return 0;
}

可见,对于成员函数drawShape(),若提供输入值,是一种执行,如果不提供输入值,是另外一种执行。和函数重载类似,但维护一个函数比维护两个函数容易,并且理解带默认参数的函数比研究两个函数的函数体更容易。另外,更新一个重载版本二忽略另外一个是导致bug的常见罪魁祸首。

既然重载问题这么多,为啥不总是使用重载呢?

答:重载提供了使用默认参数无法提供的功能,如改变参数类型,而不仅仅是改变参数数量

猜你喜欢

转载自blog.csdn.net/suyunzzz/article/details/89914653