显示信息
Coddy 用户类:面向对象编程项目 课程的第 4 课,共 8 课。
挑战
简单在 User 类中添加一个 location 属性。这个属性应为私有属性,并添加两个方法来访问它:
getLocation:返回位置。setLocation:根据函数参数设置新的位置。
location的默认值应为"unset"。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "user.h"
int main() {
User u;
User_init(&u, "", "");
char line[1024];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "new") == 0) {
char* un = strtok(NULL, " \t");
char* em = strtok(NULL, " \t");
User_init(&u, un ? un : "", em ? em : "");
}
if (strcmp(cmd, "username") == 0) { printf("%s\n", u.username); }
if (strcmp(cmd, "email") == 0) { printf("%s\n", u.email); }
if (strcmp(cmd, "setLocation") == 0) { char* v = strtok(NULL, " \t"); if (v) User_setLocation(&u, v); }
if (strcmp(cmd, "getLocation") == 0) { printf("%s\n", User_getLocation(&u)); }
}
return 0;
}
用户类:面向对象编程项目中的所有课
自己练习: C 在线编译器