1.c++中与oc中类和对象创建及访问

来源:互联网 发布:淘宝一元拍卖真的吗 编辑:程序博客网 时间:2024/05/29 04:05

目的:创建对象访问类的属性和方法

1.c++中实现

#include <iostream>

using namespace std; //使用命名空间


/**

 *   定义car

 */

class car {

private:

    int _wheels;//car属性1:车的轮子个数

   int _speed; //car属性2:车的时速

public:

   /**

     *  轮子的set方法

     */

   void setWheels(int wheels)

    {

       _wheels = wheels;

    }

   /**

     *  车的时速的set方法

     */

   void setSpeed(int speed)

    {

       _speed = speed;

    }

   /**

     *  轮子的get方法

     */

   int getWheels()

    {

       return _wheels;

    }

   /**

     *  车的时速的get方法

     */

   int getSpeed()

    {

       return _speed;

    }

    

   void run(); // 跑的方法的声明

};


void car:: run()// 车子跑的方法的实现

{

   cout << "c++中运行跑" <<"\n";

}


int main()

{

    car *A;// 创建car类型的对象

     A->setWheels(8);

   int wheels = A->getWheels();

   cout << "" << wheels <<"个轮子" <<"\n";

    A->run();// 调用car类的方法

   return 0;

}


//

int main()

{

    car A;// 创建car类型的对象

    A.setWheels(8);

   int wheels = A.getWheels();

   cout << "" << wheels <<"个轮子" <<"\n";

    A.run();

   return 0;

}

2.oc中实现

#import <Foundation/Foundation.h>


// 类的声明部分

@interface Car : NSObject

{

    @private

    int _wheels; //多少个轮子

    int _speed; //时速

}


/**

 *   set方法的声明

 */

- (void)setWheels:(int)wheels;

- (void)setSpeed:(int)speed;


/**

 *   get方法的声明

 */

- (int)wheels;

- (int)speed;


- (void)run; // run方法的声明

@end


// 类的实现部分

@implementation Car


/**

 *   set方法的实现

 */

- (void)setWheels:(int)wheels

{

    _wheels = wheels;

}

- (void)setSpeed:(int)speed

{

    _speed = speed;

}


/**

 *   get方法的实现

 */

- (int)wheels

{

    return _wheels;

}

- (int)speed

{

    return _speed;

}


// run方法的实现

- (void)run

{

    NSLog(@"oc中运行跑");

}

@end


int main()

{

    Car *mycar = [Car new]; // 创建car类型的对象

    [mycar setWheels:8];

    int wheels = [mycar wheels];

    NSLog(@"%d个轮子", wheels);

    [mycar run]; // 调用car类的run方法

    return 0;

}


// 或者

int main()

{

    Car *mycar = [Car new]; // 创建car类型的对象

    mycar.wheels = 8;

    int wheels = mycar.wheels;

    NSLog(@"%d个轮子", wheels);

    [mycar run]; // 调用car类的run方法

    return 0;

}








0 0
原创粉丝点击