我们可以像在名称空间中那样对类名进行别名吗? [英] Can we alias a class name the way we do in namespaces?

查看:80
本文介绍了我们可以像在名称空间中那样对类名进行别名吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以像在名称空间中那样对类名进行别名吗?

Can we alias a class name the way we do in namespaces?

例如:

namespace longname{ }
namespace ln = longname;// namespace aliasing

class LONGNAME {};
class LN = LONGNAME; // how to do class name aliasing, if allowed?


推荐答案

简单:

typedef LONGNAME LN;

Typedef在C ++中的用法有点像可以存储类型的变量。示例:

Typedefs are used in C++ a bit like "variables which can store types". Example:

class Car
{
public:
    typedef std::vector<Wheel> WheelCollection;

    WheelCollection wheels;
};

通过在任何地方使用 Car :: WheelCollection 代替在 std :: vector< Wheel> 中,您可以在一处更改容器类型,并使所有代码都反映出更改。这是C ++提取数据类型的方式(例如,在C#中,您将有一个属性返回 IEnumerable< Wheel> )。

By using Car::WheelCollection everywhere instead of std::vector<Wheel>, you can change the container type in one place and have all your code reflect the changes. This is the C++ way to abstract data types (whereas eg. in C# you'd have a property returning IEnumerable<Wheel>).

这篇关于我们可以像在名称空间中那样对类名进行别名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆