gpt4 book ai didi

c++ - 我怎样才能让一个类函数接受另一个对象? (C++)

转载 作者:行者123 更新时间:2023-11-28 05:56:29 25 4
gpt4 key购买 nike

我希望 Account 类保存一个人的名字、姓氏和他们的余额

Produce 类保存有关一种水果或蔬菜的信息

我希望 Account 类中的 SellProd 函数接受 Produce 对象,以便它可以将该 Produce 的价格添加到此人的余额中。截至目前,该函数给我一个错误提示“Unknown type name 'Produce'

有什么技巧可以让它发挥作用吗??

#include <iostream>
#include <string>

using namespace std;

class Account
{
friend class Produce;
private:
double funds;
string ownerfirst, ownerlast;
void addToFunds(double p) { funds += p;};
public:
Account( string first, string last) { ownerfirst = first; ownerlast = last; funds = 0;};
void printAccount()
{
cout<<"Account Holder: "<<ownerfirst<<" "<<ownerlast<<endl;
cout<<"Account Balance: "<<funds<<endl;
};
void sellProd(Produce a)
{
cout<<"Selling: "<<kind<<" | Classified as: "<<type<<endl;
cout<<"Current Balance: "<<funds<<endl<<"Sell price: "<<price<<endl;
addToFunds(price);
cout<<"New Balance: "<<funds<<endl;
};

};
class Produce
{
private:
string kind;
string type; //fruit or vegetable
double price;
public:
void printProd()
{
cout<<"Type of "<<type<<": "<<kind<<endl;
cout<<"Selling for: "<<price<<"$"<<endl;
};
Produce( string k, string t, double p) { kind = k; type = t; price = p;};
};

int main()
{
Account myAccount("John", "Doe");
myAccount.printAccount();
Produce prod1("Tomato", "Fruit", 2.99);
Produce prod2("Apple", "Fruit", 0.99);
Produce prod3("Carrots", "Vegetable", 1.49);
Produce prod4("Potato", "Vegetable", 1.29);

prod1.printProd();
myAccount.printAccount();

最佳答案

Produce是在Account之后定义的,所以当编译器看到函数的定义时,还没有看到Produce是什么.只需切换定义,使 Produce 出现在 Account 之前。

关于c++ - 我怎样才能让一个类函数接受另一个对象? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079854/

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