Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12297120
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: 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="<Width<<",Height="<Height<<",Price="<Price<    getchar();
    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

 

参考网址:

阅读(1839) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~