类函数中默认参数的使用
在类的构造函数中加入默认实参可以很方便的适用于多种情况。前几天想试用下,结果出了点小问题,记在这里,下次就不会忘记了。
为了方便查看,我把类的定义文件和实现文件和主函数都放在一个文件中了,正确的代码如下:
 #include <iostream>
#include <iostream> using namespace std;
using namespace std;
 class Color
class Color {
{ public:
public: Color(int rt = 77,int gt = 77,int bt = 77);
    Color(int rt = 77,int gt = 77,int bt = 77); void display() const;
    void display() const; private:
private: int r;
    int r; int g;
    int g; int b;
    int b; };
};
 Color::Color(int rt /* = 77 */,int gt /* = 77 */,int bt /* = 77 */)
Color::Color(int rt /* = 77 */,int gt /* = 77 */,int bt /* = 77 */) {
{ r = rt;
    r = rt; g = gt;
    g = gt; b = bt;
    b = bt; }
} void Color::display() const
void Color::display() const {
{ cout<<r<<" "<<g<<" "<<b<<endl;
    cout<<r<<" "<<g<<" "<<b<<endl; }
}
 int main()
int main() {
{ Color color1,color2(50),color3(50,60);
    Color color1,color2(50),color3(50,60); color1.display();
    color1.display(); color2.display();
    color2.display(); color3.display();
    color3.display(); return 0;
    return 0; }
}
需要注意的是,如果有默认实参的话,只需要在函数声明中给出默认实参就可以了,在函数定义时没必要给出默认实参,但一般是通过注释把默认实参注释掉,这样通读性比较高,就像上面程序所做的那样,谨记。
    我没有什么雄心壮志,我只想给自己和关心自己的家人和朋友一个交代,仅此而已。
 
                    
                

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号