首页 > 解决方案 > 做一些计数器操作,我该如何做,如果 setCounter() 没有参数,计数器为零?

问题描述

给定以下 C++ 程序:

#include "counterType.h"
#include <iostream>
#include <string>

using namespace std;

counterType::counterType()
{
    counter = 0;
}

counterType::counterType(int c)
{
    setCounter(c);
}

void counterType::setCounter(int ck)
{
    counter = ck;
}

int counterType::getCounter()
{
    return counter;
}

void counterType::incrementCounter()
{
    ++counter;
}

void counterType::decrementCounter()
{
    --counter;
}

void counterType::print()
{
    cout << "Counter = "<< counter << endl;
}

该代码似乎仅在 setCounter() 中有参数时才有效。唯一失败的测试是当 is 没有参数时。那么我如何检查它,如果没有参数,那么计数器将为 0?

标签: c++

解决方案


这是默认函数参数的完美位置。由于这是一个类成员函数,这意味着您需要将函数声明更改为

void setCounter(int ck = 0);

告诉编译器如果没有提供一个值ck,它可以0用作默认值。这意味着您的函数定义保持不变,因为它从他的声明中“拉入”了默认值。


推荐阅读