[英]Does C++ provide a way to access a class within a class without the scope resolution operator?
[英]How to access a header member type without scope resolution operator in C++?
我正在学习C ++,这可能是一个愚蠢的问题。
我想为普通类型的definitons创建一个类,并通过插入在许多cpp文件中使用它。 标题为“ CommonTypesCls.h”:
class CommonTypesCls
{
public:
typedef unsigned int UINT32;
typedef int INT32;
}
我想像这样在source.cpp中使用这些属性:
#include "CommonTypesCls.h"
int main()
{
int a = sizeof(UINT32);
return 0;
}
是否可以使用包含类的成员类型而没有范围解析?
不,除非您使用类型别名,否则是不可能的。
using UINT32 = CommonTypesCls::UINT32;
但是您不应该这样做,因为类不是收集类型定义的合适位置。
将它们放在全局范围或命名空间中。
早在Loooon之前,C ++标准就包含了用于此目的的namespace
(顺便说一句,看来您是在重新发明轮子):
#include <cstdint>
namespace CommonTypesCls {
using uint32 = std::uint32_t;
using int32 = std::int32_t;
}
int foo() {
using namespace CommonTypesCls;
uint32 a = 666;
}
如果类型是特定于特定类的,例如依赖于模板参数(例如std::vector<>::value_type
),则必须在某个地方使用范围解析运算符,但可以创建别名:
template<typename Container>
void bar(Container const&container)
{
using value_type = typename Container::value_type; // scope resolution
value_type temporary_storage[4];
for(auto const&x : container) {
/* do something with x and using temporary_storage */
}
}
但是,使用auto
变量声明时,通常不必显式指定类型。
通常,类是提供通用定义的错误方法:使用namespace
。
同样,您想要的固定大小整数类型的特定定义由<stdint.h>
。
就是说,您可以在C
派生的类中的代码中使用不合格的C
类的public
和protected
定义。 但这将使用两个通常错误的工具:提供定义的类,以及获取访问的继承。 仍然在某些情况下是合适的,例如,提供对enum
类型名称的访问。
当然:
#include "CommonTypesCls.h"
int main()
{
typedef typename CommonTypesCls::UINT32 UINT32;
int a = sizeof(UINT32);
return 0;
}
严重的是,不是真的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.