簡體   English   中英

做一些計數器操作,我該如何做,如果 setCounter() 沒有 arguments,計數器將為零?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM