gpt4 book ai didi

Objective-C - 私有(private) vs protected vs 公共(public)

转载 作者:IT老高 更新时间:2023-10-28 11:48:14 26 4
gpt4 key购买 nike

我希望在 Objective-C 中编程时,就类成员如何私有(private)、 protected 和公共(public)如何工作 - 我想我知道其中的区别(我已经在我的父类 Person 中添加了一些关于相同),但是当我尝试通过子类访问父类的私有(private) ivar/成员时编译器没有提示这一事实现在让我感到困惑。

这是我的父类:

/*
Person.h
*/

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
//We can also define class members/iVars that are of type private
//This means they can only be accessed by the member functions
//of the class defining them and not subclasses
@private
int yob;

//We can also define class members/iVars that are of type public
//Public members can be accessed directly
@public
bool alive;

//By default class members/iVars are of type protected
//This means they can only be accessed by a class's own
//member functions and subclasses of the class and typically
//also by friend functions of the class and the subclass
//We can explicitly define members to be protected using the
//@protected keyword

@protected
int age;
float height;

}
@property int age;
@property float height;
@property int yob;
@property bool alive;

@end

这是我的派生类 Man:

    /*
Man - Subclass of Person
*/

#import <Foundation/Foundation.h>
#import "Person.h"

@interface Man : Person
{
//iVar for Man
float mWeight;
}
@property float mWeight;

@end

最后,这是主要的:

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Man.h"

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//Create a Person object
Person * aPerson = [[Person alloc]init];

//Create a Man object
Man * aMan = [[Man alloc]init];

//Let's attempt to modify our Person class members
aPerson.height = 5.11; //Protected
aPerson.age = 21; //Protected
aPerson.yob = 2010; //Private
aPerson.alive = YES; //Public

//Let's now attempt to modify the same members via our
//derived class Man - in theory, the private members should
//not be accessible by the derived class man
aMan.height = 6; //Protected
aMan.age = 26; //Protected
aMan.yob = 2011; //Private
aMan.alive = YES; //Public
aMan.mWeight = 190; //Protected member of Man Class

[pool drain];
return 0;
}

编译器不应该提示我为什么尝试访问上面的 aMan.yob 吗?或者通过使用@property 和@synthesize(即setter 和getter 方法),我是否基本上使该成员受到保护,因此子类可以访问?

最佳答案

通常的技巧是在 .m 文件中创建一个类扩展名,并将您的私有(private)/ protected 属性放在那里而不是在标题中。

//Person.m

@interface Person()

@property float height

@end

这隐藏了“高度”属性

另一个技巧是如果你想创建一个只读属性是在标题中声明它作为

@property(readonly) int myproperty

但在类扩展中作为 readwrite 允许您的 .m 使用 getter/setter 修改值

@property(readwrite) int myproperty

关于Objective-C - 私有(private) vs protected vs 公共(public),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4869935/

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