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

标签 c++ class oop

#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/

相关文章:

java - 如何将 Boost::make_recursive_variant 对象转换为字符串?

c++ - 私有(private)静态变量

python - "subtracting"字符串,python 中的类

java - 编排多个 google API 客户端的最佳方法是什么?

c++ - C++中文本文件和二进制文件之间的转换

c++ - boost 。多线程

c++ - 将 pickle 添加到用 C++ 编写的 Python 扩展

c++ - 链接错误与 C++ 模板类和在单独的头文件中定义的嵌套类

c++ - 使用 C++ 操作符重载 : class with pointer datat members

java - 方法绑定(bind)中的异常行为