如何在类别内的类中访问类中的结构变量
How to access struct variables within a class, inside a different class?
我每个类都有多个文件。我正在尝试使用来自结构的数据(在第一类内部(并在第二类中使用。
我尝试将结构放在自己的文件中,但这感觉有些不必要。我已经尝试了几种编码方式,例如在Main中宣布结构并在其他类中宣布结构。
// class 1
class Shop
{
public:
struct Products
{
int price;
int quantity;
};
void SetProductValue();
private:
float register_total;
};
// class 2:
class Consumer
{
public:
Shop Products;
int total_customers;
bool buy_product(); // <--
for this?
private:
string consumer_name;
float Consumer_balance;
};
void buy_product((的功能描述是什么样的?
bool Consumer::buy_product();
{
if (consumer_balance < Products.price) return false;
if (consumer_balance >= Products.price) return true;
}
这是我尝试过的几种方法之一,我会因尝试使用产品而遇到错误。
struct Products { ... };
声明 type ,而不是产品实例。
为了在您的班级中拥有实际产品,您必须声明成员变量:
class Shop
{
public:
struct Product // no need for "s"
{
int price;
int quantity;
};
void SetProductValue();
private:
// either:
Product product; // <--- HERE
// or, if your shop has multiple products:
std::vector<Product> products;
float register_total;
};
为了访问一个特定产品(哪一种?(,您的Shop
类必须揭示某些访问器功能。一个选项是按名称选择产品:
Product Shop::GetProductByName(const std::string& name) const
{
// find right product _instance_ here
}
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 仅使用结构名称访问结构成员
- 使用内存地址访问结构的属性值
- 通过指针偏移量访问结构变量值
- 如何从实现接口的模板化类实例访问结构
- 在C++中访问结构数组中的数据
- 如何使用 pybind 访问结构的属性?
- 尝试在 qml 中访问结构成员的 QList
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- C++:从其他类访问结构的私有成员向量
- C++/CLI -- 访问结构成员
- 当我尝试访问结构类型时,我收到 std::bad_variant_access 异常
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何访问结构成员作为指针
- 为什么不能指向指针,在没有强制转换的情况下访问结构成员?
- 为什么在使用 auto_ptr 样式类访问结构成员时会出现'unidentified identifier'?
- 通过指针算法访问结构数据成员
- 通过 C++ 中的另一个结构成员访问结构