gpt4 book ai didi

C++ cout in 方法良好的编程风格

转载 作者:行者123 更新时间:2023-11-30 01:12:01 25 4
gpt4 key购买 nike

你有什么事,我应该使用 cout <<在方法中?或者我应该返回一个数组?因为我需要不止一个返回 value .

我有课 SGetraenkeAutomat , 这里是 .h文件

class SGetraenkeAutomat
{
public:
// this method
void DisplayInventory();

SGetraenkeAutomat();
SGetraenkeAutomat(int nColaAnzahl, int nSpriteAnzahl, int nFantaAnzahl);
virtual ~SGetraenkeAutomat();
private:
int m_nColaAnzahl;
int m_nSpriteAnzhal;
int m_nFantaAnzahl;
};

方法void SGetraenkeAutomat::DisplayInventory()SGetraenkeAutomat.cpp

void SGetraenkeAutomat::DisplayInventory(){
std::cout << m_nColaAnzahl;
std::cout << m_nSpriteAnzahl;
std::cout << m_nFantaAnzahl;
}

这是一种好的编程风格吗?

-> 我不这么认为,但也许你们有人可以给我解释一下。

最佳答案

我宁愿将它重命名为 PrintInventory 并提供一个可选参数:

    void PrintInventory(std::ostream &output = std::cout);

通过这种方式,您可以将库存输出到其他流,同时您不必在每次要打印到标准输出时都指定它。

void SGetraenkeAutomat::PrintInventory(std::ostream &output){
output << m_nColaAnzahl;
output << m_nSpriteAnzahl;
output << m_nFantaAnzahl;
}

这样你可以做:

automat.PrintInventory(); // prints to stdout

或者类似的东西

automat.PrintInventory(std::cerr); // prints to stderr, for example

关于C++ cout in 方法良好的编程风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34894420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com