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. 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;
}
CodePudding user response:
You can use Store as friend class of Toys which enables you to use data members of Toys class in Store class Try it !
CodePudding user response:
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.
This means, you can create an instance of type Toys::Stock
inside Store
without having any friend declaration as shown below:
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;
};