您的位置:首页 > 移动开发 > Objective-C

2.c++与objective-c中的构造方法(构造函数)

2015-09-19 14:31 579 查看
在创建类中属性定义时,不能赋初值,只能靠构造方法来实现

1.c++中的构造函数:在定义类的方法时确定

public:
    car(int w,int s)//构造函数
    {
       _wheels = w;
       _speed = s;
    }


    car(int w,
int s):_wheels(w),
_speed(s)
    {

        
    }

调用方法时赋初值

int main()
{

    car A(5,3);//创建car类型的对象时赋初值
   int wheels = A.getWheels();
   cout <<"有"
<< wheels <<"个轮子" <<"\n";
    A.run();
   return0;
}


int main()
{
   car *A =
newcar(5,
3); // 创建car类型的对象,用指针方式
   int wheels = A->getWheels();
   cout <<
"有" << wheels <<"个轮子"
<<"\n";
    A->run();
   delete A; // 内存释放
   return
0;
}

2.oc中的构造方法

/**

 *  init方法做构造方法

 */

- (instancetype)init
{
   if (self = [superinit]) {
       _wheels =4;
       _speed =20;
    }

    return
self;
}
int main()
{
   Car *mycar = [[Caralloc]init];//创建car类型的对象时会调用init方法
   NSLog(@"有%d个轮子,车速为%d",
mycar.wheels, mycar.speed);

    [mycar run];//调用car类的run方法
   return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息