gpt4 book ai didi

c - 了解编程作业的方向?

转载 作者:太空宇宙 更新时间:2023-11-04 04:57:08 25 4
gpt4 key购买 nike

我们在 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 方法的指针。

我们不是在寻找任何人为我们做这个程序。我们只是想了解我们的教授已经出城一周了,我们应该做什么。任何帮助将不胜感激。

最佳答案

这听起来像是他要你获取 Student 结构并在结构本身内部添加一个指向函数的指针,这样当你有一个指向 Student 结构的有效指针时,你可以做类似的事情

`myStudent->toString();`

并让它返回与

相同的值
`studentToString(myStudent)`

以前会有。这使得它更加面向对象,因为您正在 Student 结构的有效“实例”(由于缺乏更好的术语)上调用 toString 方法,并且返回与该“实例”相关的参数。就像您使用某种基于对象的编程语言一样。

关于c - 了解编程作业的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5601221/

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