我们在 C 编程课程中被分配了一项任务,以修改程序以使其更加面向对象。其中一部分是修复 toString 方法。方向是:
Modify the Student module to make it more object-oriented.
* Each Student object should have a function pointer that points to an
appropriate function for producing a string representation of the object.
* Provide a default toString method to each object when it is created.
The studentToString method should no longer be part of the Student interface
(as defined in Student.h)
但是,我们并不确定这意味着什么,并且想知道我们是否走在了我们应该做的正确轨道上。以下是 Student.c 文件中的代码:
#include <stdio.h>
#include <stdlib.h>
#include "Student.h"
#include "String.h"
static void error(char *s) {
fprintf(stderr, "%s:%d %s\n", __FILE__, __LINE__, s);
exit(1);
}
extern Student newStudent(char *name, int age, char *major) {
Student s;
if (!(s = (Student) malloc(sizeof(*s))))
error("out of memory");
s->name = name;
s->age = age;
s->major = major;
return s;
}
extern char *studentToString(Student s) {
const int size = 3;
char age[size + 1];
snprintf(age, size, "%d", s->age);
char *line = newString();
line = catString(line, "<");
line = catString(line, s->name);
line = catString(line, " ");
line = catString(line, age);
line = catString(line, " ");
line = catString(line, s->major);
line = catString(line, ">");
return line;
}
我们知道 *studentToString 方法将被 *toString 方法替换,我们认为 *toString 方法将与 *studentToString 方法具有相同的内容。但是我们不明白这如何使它更加面向对象。我们还从说明中确定,当我们创建一个新的 Student 对象时,我们应该在 newStudent 方法中有一个指针,该指针指向新的 toString 方法。
我们不是在寻找任何人为我们做这个项目。我们只是想了解我们应该做什么,因为我们的教授已经出城一周了。任何帮助将不胜感激。