gpt4 book ai didi

c++ - 如何将私有(private)成员变量传递给另一个类?

转载 作者:太空宇宙 更新时间:2023-11-04 13:02:51 25 4
gpt4 key购买 nike

基于我的 Snack.cpp、Snack 头文件、MiniVend 头文件和 miniVend.cpp 文件,我正在尝试将我的 Snack 私有(private)成员 - 价格移动到我的 MiniVend.cpp 文件中以生成金额 * 价格以返回总计我机器中元素的值(value)。我如何访问另一个类(class)的价格?

我的 miniVend.cpp 文件的一部分

   double miniVend::valueOfSnacks()
{

return //// I don't know how to get snacks price in here? I need to access snacks & getSnackPrice.

}

miniVend header

   #ifndef MINIVEND
#define MINIVEND
#include <string>
#include "VendSlot.h"
#include "Snack.h"
using std::string;

class miniVend
{
public:
miniVend(VendSlot, VendSlot, VendSlot, VendSlot, double); //constructor
int numEmptySlots();
double valueOfSnacks();
//void buySnack(int);
double getMoney();
~miniVend(); //desructor


private:
VendSlot vendslot1; //declare all the vending slots.
VendSlot vendslot2; //declare all the vending slots.
VendSlot vendslot3; //declare all the vending slots.
VendSlot vendslot4; //declare all the vending slots.
double moneyInMachine; //money in the machine

};
#endif // !MINIVEND

零食.cpp

    #include "Snack.h"
#include <iostream>
#include <string>

using std::endl;
using std::string;
using std::cout;
using std::cin;

Snack::Snack() //default constructor
{
nameOfSnack = "bottled water";
snackPrice = 1.75;
numOfCalories = 0;
}

Snack::Snack(string name, double price, int cals)
{
nameOfSnack = name;
snackPrice = price;
numOfCalories = cals;

}

Snack::~Snack()
{

}

string Snack::getNameOfSnack()
{
return nameOfSnack;
}

double Snack::getSnackPrice()
{
return snackPrice;
}

int Snack::getNumOfCalories()
{
return numOfCalories;
}

Snack.h file
#ifndef SNACK_CPP
#define SNACK_CPP
#include <string>
using std::string;

class Snack
{
private:
string nameOfSnack;
double snackPrice;
int numOfCalories;

public:
Snack(); //default constructor
Snack(string name, double price, int cals); //overload constructor
~Snack(); //destructor

//Accessor functions

string getNameOfSnack(); //returns name of snack
double getSnackPrice(); //returns the price of the snack
int getNumOfCalories(); //returns number of calories of snack
};



#endif // !SNACK_CPP

最佳答案

假设 getSnackPrice() 是公开的,并且 Snack.h 确实存在,您应该能够调用

snackObject.getSnackPrice() * ammount

关于c++ - 如何将私有(private)成员变量传递给另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com