简体   繁体   English

如何从 1 个类访问其他类结构

[英]How to access from 1 class to other class struct

I'm a beginner and trying to learn coding.我是初学者,正在尝试学习编码。 So please excuse if my question is stupid.如果我的问题很愚蠢,请原谅。 I have these 2 classes and I want the class Store to have access a data from struct Stock in class Toys.我有这 2 个类,我希望 Store 类能够从 Toys 类中的 struct Stock 访问数据。 I'm not sure how can I do this?我不确定我该怎么做?

#include <vector>
#include <string>
#include <iostream>

class Toys {
public:
    struct Stock
    {
        int x;
        Stock(int value)
            :x(value) {}
    };
};

class Store {
public:
    Toys myToy(int count) {
        _count = count;
    }
    Toys* myStore;
    //What do I need to do to bind a struct Stock from class Toy here?
private:
    int _count;
};

int main()
{
    Store myStore;
    int x;
    std::vector<Toys::Stock> stocks;
    std::cout << "Enter the availability for Water Gun.\n";
    std::cin >> x;
    for (int i = 0; i <= x; i++) {
        stocks.push_back(i);
        std::cout << stocks[i].x << std::endl;
    }
//Later I want to pull vector stocks from class Store here.
    return 0;
}

您可以将 Store 用作 Toys 的朋友类,这使您可以在 Store 类中使用 Toys 类的数据成员 试试吧!

Normally you'd have to add a friend declaration saying that you want to access private data from a particular class but since in your given example Stock is a struct and since you've used public access specifier inside Toys while declaring Stock , there is no need for the friend declaration here.通常,您必须添加一个朋友声明,说明您想从特定类访问私有数据,但由于在您给定的示例中Stock是一个结构,并且由于您在声明Stock时在Toys中使用了public访问说明符,因此没有这里需要朋友声明。

This means, you can create an instance of type Toys::Stock inside Store without having any friend declaration as shown below:这意味着,您可以在Store内创建类型为Toys::Stock的实例,而无需任何朋友声明,如下所示:

class Store {
public:
    
    Toys* myStore;
    
    Toys::Stock s1; // a data member named `s1` of type Toys::Stock
  
    Toys::Stock* ptr; //a data member named `ptr` of type Toys::Stock*
    int _count;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM