gpt4 book ai didi

c++ - 如何在类中将 bool 值更改为字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:13 36 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;

class Animal{
protected:
bool isMammal;
bool isCarnivorous;
public:
Animal(bool, bool, string);
bool getIsMammal(){return isMammal;}
bool getIsCarnivorous(){return isCarnivorous;}
};

Animal::Animal(bool isMammal, bool isCarnivorous){
this -> isMammal = isMammal;
this -> isCarnivorous = isCarnivorous;
}

int main(){
Animal Dog(true, true);
cout << "A dog is " << Dog.getIsCarnivorous() << ", and is a " << Dog.getIsMammal();
return 0;
}

假设我有这段代码。我期待有一个像这样的字符串输出狗是食肉动物,是哺乳动物。但相反,我得到了这个 A dog is a 1, and is a 1

我该如何解决这个问题?

最佳答案

您可以使用条件运算符:

cout << "A dog is " << (Dog.GetIsCarnivorous() ? "" : "not ") << "carnivorous, and is " << (Dog.getIsMammal() ? "" : "not ") << "a mammal.";

关于c++ - 如何在类中将 bool 值更改为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50533255/

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