c++ - 做一些计数器操作,我该如何做,如果 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?
解决方案
这是默认函数参数的完美位置。由于这是一个类成员函数,这意味着您需要将函数声明更改为
void setCounter(int ck = 0);
告诉编译器如果没有提供一个值ck
,它可以0
用作默认值。这意味着您的函数定义保持不变,因为它从他的声明中“拉入”了默认值。
推荐阅读
- c - FFTW3 3D 图像的 2D 卷积乘积
- java - Kotlin Kapt 不能与 Java 11 以及(任何)Java 注释处理库一起正常工作
- java - 为什么我收到线程 t1 的 IllegalMonitorStateException
- android - 无法计算任务 ':app:mergeLibDexDebug' 属性 'numberOfBuckets' 的值。预期 minSdkVersion >= 21 但找到 1
- python - dask 数据框:来自分区的生成器
- error-handling - 为插件域 Cpanel 创建电子邮件时出错
- python-2.7 - 如何对 Azure Data Lake 或 Blob Store 寄予厚望
- python - 为什么使用 python 在我的 sqlite 表中搜索项目仅在数据是保存为文本的数字时才有效?
- json - Swift:如何处理相同值但返回类型不同的 JSON 响应?
- javascript - 二维数组从目标位置查找值