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]; //可以編譯通過,能運行,沒有任何反應
出現這種現象主要和語言內存管理方式有段。當對象賦值爲空值的時候,指向一個空的地址,所以訪問對象的屬性,就會出現訪問異常。類的方法,在內存中的位置,位於代碼段,可以正常訪問。