访问C++中的类型成员
Accessing type members in C++
给定一个容器,如vector<int>
#include <vector>
using namespace std;
vector<int> v{1, 2, 3};
为什么访问iterator
和const_iterator
等公共类型成员似乎相当困难?据我了解,这些名称是类(而不是对象(的一部分,必须通过::
访问以指定范围,但是当已知v
时,是否有理由禁止v.const_iterator
? 例:
int f(v.iterator it) {
return *it;
}
// or
int g(v::iterator it) {
return *it;
}
解决方法是使用decltype
,如下所示:
int h(decltype(v)::iterator it) {
return *it;
}
但是这种方法甚至在类中都不起作用,因为以下方法失败了:
class A
{
public:
int h(decltype(x)::iterator it) {
return *it;
}
private:
vector<int> x;
};
编辑
只是一点旁注。 如前所述,v.iterator
的含义将取决于使用点(编译时(的v
类型,而忽略运行时多态性。但静态类成员也是如此。 例:
struct A
{
static const int x = 1;
};
struct B : public A
{
static const int x = 2;
};
void eval()
{
B b;
A& ar = b;
b.x; // 2
ar.x; // 1, even though ar refers to the same underlying object (by the base type)
}
正如@Slava评论中指出的那样,decltype(x)
是这样做的方法:
#include <vector>
using namespace std;
vector<int> v{1, 2, 3};
int f(decltype(v)::iterator it) {
return *it;
}
int g(decltype(v)::iterator it) {
return *it;
}
class A
{
private:
vector<int> x;
public:
int h(decltype(x)::iterator it) {
return *it;
}
};
成员访问运算符和范围解析运算符.
::
不得过载。正如您可能从名称中推断的那样,.
用于访问成员,而::
用于访问范围。
#include <iostream>
struct B {
class iterator { };
// no need for typename, compiler knows that we mean typedef B::iterator, as he can only find it
iterator iterator1;
// member named the same as class, ops!
int iterator;
// we need to use typename here, B::iterator is resolved as member
// iterator iteartor3;
typename B::iterator iterator2;
};
int main() {
B bobj;
// we access the member iterator inside b
bobj.iterator = 1;
// we declare object of B::iterator type
// we need to tell compiler that we want only types
typename B::iterator iterator;
// this will work too
typename decltype(bobj)::iterator iterator2;
// we declare a member pointer to the iterator member inside some B class
// no typename, as I want pointer to member, not pointer to... type
int B::* pointer = &B::iterator;
// this is just a pointer to the iterator specifically in bobj class
int * pointer2 = &bobj.iterator;
// foo(bar)
bobj.*pointer = 1;
// this will work as expected
int decltype(bobj)::* pointer3 = &B::iterator;
}
此外,C++中没有"类型成员"(至少我在标准C++找不到它们(。类和枚举以及类中声明为成员的 typedefs 声明称为"嵌套类型"或"嵌套类"。
基本上,C++允许您在通过::
访问它们时获取值或类型。所以MyType::AnotherType
很好,也MyType::AValue
.当您使用.
遍历实例时,它仅表示它想要解析一种值(字段、func 等(的符号。希望有帮助。
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员