【问题标题】:Using a class as a value type within another class in the header file在头文件的另一个类中使用一个类作为值类型
【发布时间】:2012-05-11 01:58:51
【问题描述】:

我在编写自助餐厅模拟项目时遇到了另一个问题。这个想法是我正在编写三个类(student、group 和 tray)和一个主程序来模拟正在运行的自助餐厅。 托盘包含某些信息,例如颜色和拿起它的学生的姓名,以及托盘上食物加起来的总数量。在每个traystudent配对后,将其推入group堆栈。这就是问题出现的地方。尝试使用 tray 参数定义 group 函数时出现各种错误。以下是这两个类的代码以及一些错误,再次,我将不胜感激:

    class group
{
public:
    //CONSTRUCTOR
    group(string color="nocolor"){group_color=color; group_total=0;}
    //MEMBER FUNCTIONS for group class:
    void set_color(string new_color){group_color=new_color;}
    void add_member(simic_217A::tray new_member){assert(group_color==new_member.color());members.push(new_member);group_total+=new_member.price();}
    //void add_it_up();
    void remove_one() {members.pop();}
    void empty_group(){assert(!members.empty()); while(!members.empty()){members.pop();}} //    NEWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWw

    //CONST MEMBER FUNCTIONS for group class:
    string color() const {return group_color;}
    double  price_tot() const {assert(!members.empty()); return group_total;}
    bool is_empty() const {return members.empty();}
    simic_217A::tray top_item() const {return members.top();}

private:
    double group_total;
    string group_color;
    stack<simic_217A::tray> members;
};

//NONMEMBER FUNCTION for group class:
    std::ostream& operator <<(std::ostream& outs, const group& info);


class tray
{
public:
    //CONSTRUCTOR
    tray(string color="nocolor"){tray_color=color; tray_student_name="noname"; tray_price=0;}
    //MEMBER FUNCTIONS for tray class:
    void pick_up(student nextinline){tray_student_name= nextinline.get_name(); tray_price= nextinline.price(); nextinline.set_group(tray_color) ;}
    string set_color(string color){tray_color=color;}
    void drop_tray(){tray_student_name="noname"; tray_price=0;} 
    //CONST MEMBER FUNCTION for tray class:
    string tray_name() const {return tray_student_name;}
    double tray_price_func() const {return tray_price;}
    string color () const {return tray_color;}
private:
    string tray_color;
    string tray_student_name;
    double   tray_price;
};
  }

以下是我在尝试编译时遇到的几个错误:

    error C2039: 'tray' : is not a member of 'simic_217A'

    error C2061: syntax error : identifier 'tray'

    error C2146: syntax error : missing ';' before identifier 'top_item'

【问题讨论】:

    标签: c++ class object header


    【解决方案1】:

    托盘的定义需要出现在任何依赖它的类之前,例如组。否则编译器将不知道托盘是什么。

    【讨论】:

    • 谢谢,我不知道编译器不会识别它。因此,如果我的每个班级都包括其他两种类型中的每一种(例如/组有托盘和学生类型,托盘有组和学生类型等),我将不得不切换一些东西以便能够编译,对吧? (这可能是一个不现实的情况,但我想知道是否有任何方法可以解决这个问题)
    • @Mike 你得到的是一个循环依赖。应该通过改变你的类设计来避免它们,这样做有很多技巧,比如Observer pattern
    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    相关资源
    最近更新 更多