如何将函数插入数据结构?

时间:2011-12-06 11:29:49

标签: c++ function data-structures

在数据结构中,如何插入函数?

struct Student_info {
std::string name;
double midterm, final;
unsigned int& counter;
std::vector<double> homework;
double overall = grade(students[counter]);
};

总是会遇到这种错误: -

一个。 “变量”未在此代码中声明。

湾“Student_info :: counter”不能出现在常量表达式中。

℃。数组引用不能出现在常量表达式中。

d。函数调用不能出现在常量表达式

编辑: - oopps,我的意思是student_info包含在一个向量中,等等,为什么还需要这些信息...... Dx

哦,顺便说一句,这是来自Accelerated C ++,显然是一本书,而我正试图回答其中的一个练习,然后我需要知道这一部分,而不是在Dx上找到任何一本

问题是4-6。重写Student_info结构以立即计算成绩并仅存储最终成绩。

1 个答案:

答案 0 :(得分:4)

您可以 NOT 动态地将函数插入结构中。

您可以声明具有方法()

的结构
struct Student_info
{
    void doDomethingToStudent()
    {
         // Manipulate the object here.
    }
    // STUFF
};

此外,您无法像上面那样初始化成员。

double overall = grade(students[counter]);

在这里,您需要创建将初始化成员的构造函数。

struct Student_info
{
    Student_info(std::string& studentName, unsigned int& externalCounter)
        : name(studentName)
        , midterm(0)
        , final(0)
        , counter(externalCounter)
        , homework()

        // It is not clear if overall is a normal memeber
        // Or a static member of the class
        , overall(grade(students[counter]))
    {}
    // STUFF
};
int main()
{
    unsigned int counter   = 0;
    Student_info bob("Bob", counter);
}