error: interface type cannot be statically allocated 学习object-c的时候遇到的小问题

本文通过一个具体的示例展示了如何在Objective-C中定义类并实现对象之间的交互,包括属性的设置和方法的调用,强调了指针在面向对象编程中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

赖和英文水平有限,百度了好半天,知道了,意思,才解决的.

就是object的类对象,必须有一个指针指向他.

就是必须要指针指向对象,

错误代码为:

typedef enum {
    SexMan,
    SexWoman
} Sex;
typedef struct {
    int year;
    int mothe;
    int day;
} Born;


#import <Foundation/Foundation.h>


@interface Dog : NSObject
{
@public
    char *name;
    int tizhong;
}
-(void)run;
@end

@implementation Dog
-(void) run
{
    NSLog(@"%s 遛狗 后 体重:%d",name,tizhong);
}

@end



@interface Student : NSObject
{
    @public
    char *name;
    Born born;
    Sex sex;
    int age;
    int tizhong;
    int count;
    
    //狗
    Dog *dog;
}
-(void) eat;
-(void) run;
-(void) info;
-(void) liugou;
@end

@implementation Student
-(void)liugou
{
    [dog run];
    NSLog(@"%s 狗遛了后,体重 %d",dog->name,dog->tizhong);
}
-(void)eat
{
    ++tizhong;
    NSLog(@"吃了后体重:%d",tizhong);
}
-(void) run
{
    --tizhong;
    NSLog(@"跑了步后体重:%d",tizhong);
}
-(void) info
{
    NSLog(@"name:%s,born:%d-%d-%d,sex:%d,age:%d,tizhong:%d",name,born.year,born.mothe,born.day,sex,age,tizhong);
}
@end


//类 必须声明,成员变量
@interface Car : NSObject
{
    @public
    char name;
    int year;
}
- (void) run;
@end

int main()
{
    /*
    Car *c1 = [Car new];
    c1->name='n';
    c1->year=13;
    [c1 run];
     */
    Student *stu = [Student new];
    stu->tizhong=50;
    stu->sex=SexWoman;
    Born b={1999,9,9};
    stu->born=b;
    stu->born.day=10;
    stu->name="tom";
    stu->age=15;
    Dog g = [Dog new];
    g->name="diandian";
    g->tizhong=20;
    
    stu->dog=g;
    
    [stu liugou];
    
    [stu info];
    [stu eat];
    [stu eat];
    [stu run];
    [stu run];
    
    return 0;
}

//test函数,属于文件的,
//注意不能放到类的声明中
void test()
{
    NSLog(@"调用了test函数。");
}

@implementation Car
//对象函数,必须写 -
-(void) run
{
    test();
    test2();
    NSLog(@"%c run,%d year",name,year);
}

void test2()
{
    NSLog(@"调用了test2函数。");
    
}
@end




其实就修改一句

car.m:102:9: error: interface type cannot be statically allocated

Dog g = [Dog new];
//改为
Dog *g = [Dog new];




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值