- #import <Foundation/Foundation.h>
- //定义类:人
- @interface Person : NSObject
- {
- NSString *_name; //姓名
- int _age; //年龄
- }
- //姓名的set和get方法声明
- - (void)setName:(NSString *)newname;
- - (NSString *)name;
- //年龄set和get方法声明
- - (void)setAge:(int)newage;
- - (int)age;
- //同时录入姓名和年龄方法声明
- - (void)setName:(NSString *)name2 andAge:(int)age2;
- @end
- @implementation Person
- //姓名set方法实现
- - (void)setName:(NSString *)newname
- {
- _name = newname;
- }
- //姓名get方法实现
- - (NSString *)name
- {
- return _name;
- }
- //年龄set方法实现
- - (void)setAge:(int)newage
- {
- _age = newage;
- }
- //年龄get方法实现
- - (int)age
- {
- return _age;
- }
- - (void)setName:(NSString *)name2 andAge: (int)age2
- {
-
- [self setName : name2];
- [self setAge : age2];
- }
- @end
- int main()
- {
- Person *p = [Person new];
- [p setName:@"jack" andAge:22];
- //[p setName : @"jack"];
- //[p setAge : 22];
-
-
- NSLog(@"%@ %d",[p name],[p age]);
- return 0;
- }
复制代码 一开始我就错误的将NSLog(@"%@ %d",[p name],[p age])写成了NSLog(@"%@ %d",[p _name],[p _age]),想当然的认为要输出变量的值只要把变量拿过来就可以了,此代码中有封装set和get方法,所以输出要通过get方法的来输出
|
|