gpt4 book ai didi

c++ - 在 C++ 中访问类型成员

转载 作者:行者123 更新时间:2023-11-28 04:30:52 24 4
gpt4 key购买 nike

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

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

为什么像iterator这样的public类型的成员好像很难访问和 const_iterator ?据我了解,这些名称是类的一部分(不是对象),必须通过 :: 访问。指定范围,但是否有理由禁止 v.const_iterator什么时候v是已知的?示例:

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;
}
};

成员访问 . 运算符和作用域解析运算符 :: 不得重载。正如您可能从名称中推断的那样,. 用于 access members ,而 :: 用于访问 scope .

#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++ 标准中找不到它们)。在类中声明为成员的类和枚举以及 typedef 声明称为“嵌套类型”或“嵌套类”。

关于c++ - 在 C++ 中访问类型成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52992280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com