C++类与对象跟C#的异同

第一、抽象逻辑相同

        都是把现实世界的事与物,抽象写成类(比如钟表设计图),然后实例化成对象后使用(如果由设计图生产出了一个表)。构造与析构是一样的,有默认的,与可以自定义。

第二、大多数关键字相同,如Class,public,private,protected等,但写法不一样

        C++

        public:下面,可以跟好多个方法,以及属性。

        C#

        每个方法跟属性后面,都要带个公有私有定义。

        public void setTime(int nowH,int nowM,int nowS)         

第三、文件形式不同

        C++,创建一个类,会同时创建两个文件,一个是h头文件(这个文件有点像C#的接口),另一个是cpp实现文件。

        C#,创建一个类,只会新建一个CS文件。

 第四、主函数入口定义不一样

        C++,默认为int main(),需要返回整型主方法。

        C#,static void Main(string[] args),是个静态,还返空的主方法。

第五、实例化方式不同,但调用方式一样。

        C++,

        Clock Clock1;//实例化
        Clock1.showTime();//调用

        C#,

        Clock Clock1 = new Clock();//实例化

        Clock1.showTime();//调用

C++代码(以钟表类为例):

文件1:Clock.h,以下是代码

#ifndef CLOCK_H_
#define CLOCK_H_

class Clock {
public:
    Clock();

    void setTime(int nowH,int nowM,int nowS);
    void showTime();

virtual ~Clock();

private:
    int hours;
    int min;
    int sec;

};
#endif /* CLOCK_H_ */

文件2:Clock.cpp,以下是代码

#include <iostream>

#include "Clock.h"
using namespace std;


Clock::Clock() {
    // TODO Auto-generated constructor stub
    hours = 0;
    min = 0;
    sec = 0;
}

void Clock:: setTime(int nowH,int nowM,int nowS){
    hours = nowH;
    min = nowM;
    sec = nowS;
}

void Clock:: showTime(){

    cout << hours << ":" << min << ":" << sec << endl;

}

Clock::~Clock() {
    // TODO Auto-generated destructor stub
}

文件3:CPPBase.cpp,以下是代码

#include <iostream>
using namespace std;
#include "Clock.h"

/*
程序入口函数
*/
int main()
{
    cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!

    Clock Clock1;
    Clock1.showTime();
    Clock1.setTime(12,12,12);
    Clock1.showTime();

    return 0;
}

C#代码(以钟表类为例):

文件1:Clock.cs,以下是代码

  class Clock
   {
        private int hours;
        private int min;
        private int sec;
        public Clock()  // 构造函数
        {
            Console.WriteLine("对象已创建");
        }
        ~Clock() //析构函数
        {
            Console.WriteLine("对象已删除");
            Console.ReadLine();
        }

        public void setTime(int nowH,int nowM,int nowS)

        {
            hours = nowH;
            min = nowM;
            sec = nowS;

        }
        public void showTime()

        {

            Console.WriteLine(hours + ":"+ min + ":" + min );

        }       
    }

文件2:Program.cs,以下是代码

public class Program

{

        static void Main(string[] args)
        {
            Clock Clock1 = new Clock();

            Clock1.showTime();
            Clock1.setTime(12,12,12);
            Clock1.showTime();           
        }

}

猜你喜欢

转载自blog.csdn.net/harryxia2014/article/details/122923375