给定一个容器,例如vector<int>
#include <vector>
using namespace std;
vector<int> v{1, 2, 3};
为什么访问公共类型成员(例如iterator
and const_iterator
?据我了解,这些名称是类(而不是对象)的一部分,必须通过::
指定范围,但有理由禁止吗v.const_iterator
when v
是已知的吗?
例子:
int f(v.iterator it) {
return *it;
}
// or
int g(v::iterator it) {
return *it;
}
解决方法是使用decltype
as in:
int h(decltype(v)::iterator it) {
return *it;
}
但这种方法甚至在课堂上不起作用,因为以下失败:
class A
{
public:
int h(decltype(x)::iterator it) {
return *it;
}
private:
vector<int> x;
};
Edit
只是一点旁注。
正如所指出的,其含义是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;
}
};
会员访问.
运算符和范围解析运算符::
不得超载。正如你可以从名字中推断出的那样,.
习惯于访问成员, while ::
用于访问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 声明称为“嵌套类型”或“嵌套类”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)