全部博文(1293)
分类: C#/.net
2015-10-21 17:26:00
CSharp的new语句:
Bus myBus = new Bus(2, 3, (float)250000.0);
CPP的new语句:
Bus* myBus = new Bus(2,3,250000.0);
本质上这两条语句是一样的,都是使用new来申请分配内存。
CSharp new完成,将内存地址赋给引用myBus;CPP new完成,将内存地址赋给指针变量myBus。
下面两个代码案例分别示范CSharp和CPP继续有参数的基类、使用new关键字的用法:
CPP版本:
#include "stdafx.h"
#include
using namespace std;
class Vehicle
{
public:
Vehicle(int width,int height)
{
this->Width = width;
this->Height = height;
}
public:
int Width;
int Height;
};
class Bus : public Vehicle
{
public:
Bus(int width,int height,float price):mSeatCount(5),Vehicle(width,height),MAX_SPEED(100)
{
this->Price = price;
}
public:
float Price;
private:
static const int SEQ_NUM = 0001; //只有静态常量整型数据成员才能在类中初始化
int mSeatCount;
const int MAX_SPEED;
};
int _tmain(int argc, _TCHAR* argv[])
{
Bus* myBus = new Bus(2,3,250000.0);
cout<<"MyBus's Width="<
return 0;
}
}
CSharp版本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharpNewOperator
{
public class Program
{
class Vehicle
{
public Vehicle(int width, int height)
{
this.Width = width;
this.Height = height;
}
/* 公有成员每个都要挂上public,不然会被当成private处理 */
public int Width;
public int Height;
};
class Bus : Vehicle
{
public Bus(int width,int height,float price) : base(width,height)
{
this.Price = price;
}
private
static int SEQ_NUM = 0001; //不允许同时使用const static修饰一个整型变量
int mSeatCount = 7;
const int MAX_SPEED = 120;
public float Price = 25000;
};
static void Main(string[] args)
{
Bus myBus = new Bus(2, 3, (float)250000.0);
Console.WriteLine("MyBus'Width={0},Height={1},Price={2}\n", myBus.Width, myBus.Height, myBus.Price);
Console.ReadLine();
}
}
}
明显CPP在派生类的构造函数的初始化列表更为复杂些。
CPP在派生类的构造函数的初始化列表将专门探讨。
运行效果:
MyBus'Width=2,Height=3,Price=250000
参考网址: