基于我的Snack.cpp,Snack头文件,MiniVend头文件& miniVend.cpp文件,我试图将我的Snack私有成员 - 价格移动到我的MiniVend.cpp文件中以生成金额*价格以返回我机器中项目的总价值。如何从其他班级获取价格?
我的miniVend.cpp文件的部分
#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
miniVend标题
#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
Snack.cpp
public sealed class ArrayWrapper<T> {
private readonly T[] _array;
public ArrayWrapper(T[] array) {
if (array == null) throw new ArgumentNullException(nameof(array));
_array = array;
}
public T this[int i] {
get { return _array[i]; }
set { _array[i] = value; }
}
}
答案 0 :(得分:0)
假设getSnackPrice()是公共的,并且Snack.h确实存在,那么你应该可以调用
snackObject.getSnackPrice() * ammount
答案 1 :(得分:0)
你需要的是朋友关键词。
friend class className;
答案 2 :(得分:0)
我真的不明白你为什么不实施get()
?访问私人数据真的很糟糕。你打破了封装。但是如果你真的想知道(即你不应该这样做,那真的很糟糕),那么你只需要返回对私人数据的引用,如下所示
#include <iostream>
class A
{
public:
A(int a) : x(a) {}
int &getPrivateDataBAD() { return x; }
void print() { std::cout << x << std::endl; }
private:
int x;
};
class B
{
public:
void print(int &s) { std::cout << s << std::endl; }
};
int main()
{
A obj(2);
B bObj;
bObj.print( obj.getPrivateDataBAD() );
return 0;
}