做一些计数器操作,我该如何做,以便如果setCounter()没有参数,则计数器将为零?

0 c++

给定以下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;
}
Run Code Online (Sandbox Code Playgroud)

该代码似乎仅在setCounter()中包含参数时才起作用。唯一失败的测试是when是无参数的。那么,如何以某种方式检查它,如果没有参数,则计数器将为0?

Nat*_*ica 5

这是默认函数参数的理想位置。由于这是一个类成员函数,因此您需要将函数声明更改为

void setCounter(int ck = 0);
Run Code Online (Sandbox Code Playgroud)

告诉编译器,如果未提供该值ck,则可以将其0用作默认值。这意味着您的函数定义保持不变,因为它可以“声明”声明中的默认值。