了解编程分配的方向?

我们在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 %sn", __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
方法并返回与该“实例”相关的参数。正如您在某种基于对象的编程语言中所做的那样。     
我的猜测是你需要在Student结构中添加一个成员,该成员的类型将是一个函数指针。 然后定义该功能。 然后添加一个带有函数指针的参数给newStudent。 然后将新创建的成员设置为参数的值。 (这感觉就像是一种非常抽象的学习OO的方式,但这只是我的意见)     
看起来你的教授为你解决了这个问题,这样你就可以了解多态性。在这个例子中,我们的想法是系统中的每个对象都应该有自己的方式将自己呈现为一个字符串,但你不想知道细节;你只想在任何物体上打电话给
toString
。 例如。
banana->toString()
apple->toString()
    

要回复问题请先登录注册