c++中与这个类定义等价的是什么?

What is the c++ equivalent of this class definition

本文关键字:是什么 定义 c++      更新时间:2023-10-16

我正试图学习c++,但我的第一语言是Python。我正在努力理解c++中的构造函数,更具体地说,是可变大小的数组和字符串。有没有人能写出下面类定义的c++等效代码,这样我就可以遵循这个逻辑了?

class Fruit(object):
    def __init__(self, name, color, flavor, poisonous):
        self.name = name
        self.color = color
        self.flavor = flavor
        self.poisonous = poisonous
class Fruit {
    std::string name;
    std::tuple<uint8_t, uint8_t, uint8_t> color; // for RGB colors
    std::string flavor; // Assuming flavor is a string
    bool poisonous;
    Fruit(const std::string& nm, const std::tuple<uint8_t, uint8_t, uint8_t>& clr, const std::string& flvr, const bool psns) : name(nm), color(clr), flavor(flvr), poisonous(psns) {}
}

__init__函数的作用与c++中的构造函数非常相似。因为在c++中,您需要指定变量类型,我采取了一些自由假设nameflavor是字符串,color是一个值从0到255 (RGB)的3元组,poisonous是一个布尔值(bool)。