类函数中默认参数的使用

      在类的构造函数中加入默认实参可以很方便的适用于多种情况。前几天想试用下,结果出了点小问题,记在这里,下次就不会忘记了。

      为了方便查看,我把类的定义文件和实现文件和主函数都放在一个文件中了,正确的代码如下:

#include <iostream>
using namespace std;

class Color
{
public:
    Color(
int rt = 77,int gt = 77,int bt = 77);
    
void display() const;
private:
    
int r;
    
int g;
    
int b;
}
;

Color::Color(
int rt /* = 77 */,int gt /* = 77 */,int bt /* = 77 */)
{
    r 
= rt;
    g 
= gt;
    b 
= bt;
}

void Color::display() const
{
    cout
<<r<<" "<<g<<" "<<b<<endl;
}


int main()
{
    Color color1,color2(
50),color3(50,60);
    color1.display();
    color2.display();
    color3.display();
    
return 0;
}

 

      需要注意的是,如果有默认实参的话,只需要在函数声明中给出默认实参就可以了,在函数定义时没必要给出默认实参,但一般是通过注释把默认实参注释掉,这样通读性比较高,就像上面程序所做的那样,谨记。

 

posted on 2009-04-14 10:18  笔记  阅读(478)  评论(0编辑  收藏  举报

导航