A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 为梦想挺身而出 于 2014-7-18 11:22 编辑

  1. #import <Foundation/Foundation.h>

  2. //成绩
  3. @interface Score : NSObject
  4. {
  5.     int _cScore;
  6.     int _ocScore;
  7. }
  8. - (void)setCScore:(int)cScore;
  9. - (int)cScore;

  10. + (void)test;

  11. @end

  12. @implementation Score

  13. - (void)setCScore:(int)cScore
  14. {
  15.     _cScore = cScore;
  16. }
  17. - (int)cScore
  18. {
  19.     return _cScore;
  20. }
  21. + (void)test
  22. {
  23.     NSLog(@"调用你了test函数");
  24. }

  25. @end

  26. //学生
  27. @interface Student : NSObject
  28. {
  29.     //组合,使Student拥有Score的成员变量
  30.     Score *_score;
  31.     int _weight;
  32. }

  33. @end

  34. @implementation Student

  35. @end

  36. int main()
  37. {
  38.     //这里报错
  39.     Student *s = [Student new];
  40.     [s setCScore:90];
  41.     NSLog(@"这个学生的成绩是%d分", [s cScore]);
  42.     [Student test];
  43.     /*问题
  44.      1.继承有子类与父类之说,组合有没有
  45.      2.组合里面的成员变量如何使用啊
  46.      */
  47.    
  48.    
  49.     return 0;
  50. }
复制代码

2 个回复

倒序浏览

  1. #import <Foundation/Foundation.h>

  2. //成绩
  3. @interface Score : NSObject
  4. {
  5.     int _cScore;
  6.     int _ocScore;
  7. }
  8. - (void)setCScore:(int)cScore;
  9. - (int)cScore;

  10. + (void)test;

  11. @end

  12. @implementation Score

  13. - (void)setCScore:(int)cScore
  14. {
  15.     _cScore = cScore;
  16. }
  17. - (int)cScore
  18. {
  19.     return _cScore;
  20. }
  21. + (void)test
  22. {
  23.     NSLog(@"调用你了test函数");
  24. }

  25. @end

  26. //学生
  27. @interface Student : NSObject
  28. {
  29.     //组合,使Student拥有Score的成员变量
  30.     Score *_score;
  31.     int _weight;
  32. }

  33. // 这个要写全
  34. - (void)setScore:(Score *)score;
  35. - (Score *)score;
  36. @end

  37. @implementation Student

  38. - (void)setScore:(Score *)score
  39. {
  40.     _score = score;
  41. }
  42. - (Score *)score
  43. {
  44.     return _score;
  45. }

  46. @end

  47. int main()
  48. {
  49.     //这里报错
  50.     Student *s = [Student new];
  51.    
  52.     // [s setCScore:90]; // 你这个是继承的时候的写法
  53.    
  54.    
  55.     Score *sc = [Score new]; // 组合并不能直接调用score里的内容,需要你先创建一个Score对象,然后把这个对象给Student
  56.     [sc setCScore:90];
  57.    
  58.     [s setScore:sc];
  59.    
  60.     // NSLog(@"这个学生的成绩是%d分", [s cScore]);这是错误的
  61.    
  62.     // 应该是用Student中的score这个对象属性去调用Score这个对象里的属性
  63.      NSLog(@"这个学生的成绩是%d分", [[s score] cScore]);
  64.    
  65.     // test是Score的类方法,不能用Student去调用
  66.     // [Student test];
  67.    
  68.     /*问题
  69.      1.继承有子类与父类之说,组合有没有
  70.      2.组合里面的成员变量如何使用啊
  71.      */
  72.    
  73.    
  74.     return 0;
  75. }
复制代码


回复 使用道具 举报
[[s score] cScore]
这里的[s score] 就是sc
明白了 谢谢!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马