C++ : 类型的别名和对象的别名

9 views
Skip to first unread message

陈希章

unread,
Aug 5, 2009, 4:07:32 AM8/5/09
to chenx...@googlegroups.com
标题:
C++ : 类型的别名和对象的别名

时间:
2009/8/5 8:07:00

地址:
http://www.cnblogs.com/chenxizhang/archive/2009/08/05/1539662.html

分类:
[随笔分类]C++,


博客:
博客园

作者:
陈希章

上一篇我们讲到过,引用其实是对象的一个别名。我们知道对象是类型的具体化实例,那么类型可不可以有别名呢?答案是可以的

 

#include <iostream>
using namespace std;

class human{
public:
    void Talk();
    ~human(){cout<<"析构函数在工作..."<<endl;}
private:
    int age;
};

void human::Talk(){
    cout<<"Hello"<<endl;
}

int main()
{

    typedef human people;
    //这是定义一个类型别名,或者叫做同义词。human是原类型,people是新类型
    people p;
    p.Talk();

    human &b=p;//这是定义一个对象别名,引用了p这个对象
    b.Talk();

    return 0;
}

 

而typedef关键在在C#中并没有对应的实现,要想对类型设置别名,C#的做法大致如下

using System;
using System.Collections.Generic;
using System.Text;

using people = CSharpProject.Human;

namespace CSharpProject
{
    class Program
    {
        static void Main(string[] args)
        {
            people p = new Human();
            p.Age = 50;
            p.Talk();

            Console.Read();
        }
    }

    class Human {
        public int Age { get; set; }
        public void Talk() { Console.WriteLine("Hello,world"); }
    }
}

本文由作者:陈希章 于 2009/8/5 16:07:20 发布在:博客园,转载请注明出处

Reply all
Reply to author
Forward
0 new messages