[英]Doing some counter manipulation, how do I make it so that if setCounter() has no arguments, the counter would be zero?
给定以下 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?
这是默认 function 参数的理想位置。 由于这是一个 class 成员 function 这意味着您需要将您的 function 声明更改为
void setCounter(int ck = 0);
告诉编译器如果没有为ck
提供值,它可以使用0
作为默认值。 这意味着您的 function 定义保持不变,因为它从声明中“拉入”了默认值。
两种方法:
1)在 function 声明中提供一个默认参数,这样您就可以在不提供它的情况下调用 function。
void setCounter(int ck = 0);
2)重载function
void counterType::setCounter()
{
counter = 0;
}
一些软件公司(尤其是那些代码标准是 Java 的人)不允许第一种样式。 不喜欢第一种方式的一个不那么滑稽的原因是默认参数值可以是运行时可评估的(可能是成员变量)并且会损害程序的稳定性。
对于初学者,您可以在 class 定义中的数据成员声明中初始化数据成员counter
。 例如
class counterType
{
//...
int counter = 0;
};
在这种情况下,构造函数看起来像
counterType::counterType()
{
}
counterType::counterType(int c) : counter( c )
{
}
或者您可以通过以下方式定义构造函数
counterType::counterType() : counterType( 0 )
{
}
counterType::counterType(int c) : counter( c )
{
}
function setCounter
可以有一个默认参数
void counterType::setCounter(int ck = 0 )
{
counter = ck;
}
最好在 class 定义中声明 function getCounter
int getCounter() const;
因为 function 不会改变 object 本身。 并将其定义为
int counterType::getCounter() const
{
return counter;
}
还有这个 function
void counterType::print()
{
cout << "Counter = "<< counter << endl;
}
最好像这样声明和定义
std::ostream & print( std::ostream &os = std::cout ) const;
并将其定义为
std::ostream & print( std::ostream &os = std::cout ) const;
{
return os << "Counter = "<< counter << endl;
}
它也不会更改 object 本身,因此应使用限定符const
声明它。
看起来您的 class 只有一个数据成员,然后您可以为整个 class 定义operator <<
。 例如
class counterType
{
//...
friend std::ostream & operator <<( std::ostream &os, const counterType &c );
};
std::ostream & operator <<( std::ostream &os, const counterType &c )
{
return os << "Counter = "<< c.counter << endl;
}
你的意思是这样的吗?
void counterType::setCounter()
{
counter = 0;
}
What you're trying to achieve is called function overloading : given a different list of arguments, C++ lets you define a different "version" of the same function.
void counterType::setCounter() // No argument in there
{
counter = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.