访问C++中的类型成员

Accessing type members in C++

本文关键字:类型 成员 C++ 访问      更新时间:2023-10-16

给定一个容器,如vector<int>

#include <vector>
using namespace std;
vector<int> v{1, 2, 3};

为什么访问iteratorconst_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 等(的符号。希望有帮助。