c++ 代码,类对象赋值为空值
class test
{
public:
int age;
char* name;
void say()
{
std::cout<<"hello my name is "<<name<<std::endl;
}
void greet()
{
std::cout<<"hello\n";
}
};
test *one = nullptr;
one->age=123 //不能访问,运行错误
one->say(); //运行错误,崩溃
one->greet(); //可以运行
oc 代码,对象赋值为空值
@interface class test:NSObject
{
@public:
NSString* _name;
int _age;
}
-(void)say;
-(void)greet;
@implementation test
-(void)say
{
NSLog(@"hello my name is %@", _name);
}
-(void)greet
{
NSLog(@"hello");
}
@end
test* one = nil;
one->_name = @"lucy" //不能运行
[one say]; //可以编译通过,能运行,没有任何反应
[one greet]; //可以编译通过,能运行,没有任何反应
出现这种现象主要和语言内存管理方式有段。当对象赋值为空值的时候,指向一个空的地址,所以访问对象的属性,就会出现访问异常。类的方法,在内存中的位置,位于代码段,可以正常访问。