奇怪,vector的iterator不能有指针的用法 "->" ??

nbb 2003-10-08 07:36:30
#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

class Struct1{
public:
int a;
char * b;
Struct1(): a(0),b(0){} //初始化为0
};
class Vec1{
public:
typedef std::vector<Struct1> Arraytp;
Arraytp array;
Arraytp::iterator it;

Vec1(){
array.push_back(Struct1());
array.push_back(Struct1());
it=array.begin();
}
char* test(char* p1){
return p1-
(it->b); //故意分成两行来写,编译时指示这里有错: C2440
}
};

int _tmain(int argc, _TCHAR* argv[])
{
char* pa=(char*)0x10000000;
Vec1 ary;
char* pc=ary.test(pa);
cout<<"char* pc="<<(long)pc<<endl;
return 0;
}

//错误原因: C2440
//k:\sztst.cpp(30) : error C2440: “return” : 无法从“__w64 int”转换为“char *”

//试过reinterpret_cast、C 样式转换也无效,还是C2440, 什么原因????
...全文
96 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxjddd 2003-10-08
  • 打赏
  • 举报
回复
接分咯

我想我说的没错吧。哈哈

两个指针相减的结果的类型,应该是类似于 size_t 的,是 ptrdiff_t 吧。这个一个整型的。
nbb 2003-10-08
  • 打赏
  • 举报
回复
晕死,偶想知道原因, 真是 cxjddd(战士编程) 说的吗?
nbb 2003-10-08
  • 打赏
  • 举报
回复
“另外的,楼主,如果你把 ; 前面再插入一个回车,你会发现:错误在分号那里”

---奶奶的! 真是这样
nbb 2003-10-08
  • 打赏
  • 举报
回复
这样就可以了.
char* test(char* p1){
return (char*)(p1-(it->b));
}
这个函数的逻辑通常是错误的.

---按这个方案通过了,能详细解释一下原因吗?
Wolf0403 2003-10-08
  • 打赏
  • 举报
回复
另外的,楼主,如果你把 ; 前面再插入一个回车,你会发现:错误在分号那里^_^
cxjddd 2003-10-08
  • 打赏
  • 举报
回复
早我一步,呜呜
cxjddd 2003-10-08
  • 打赏
  • 举报
回复
晕死!不是 it 没有 -> 运算符,而是:

p1 - (it->b) 的结果是 int,而 Vecl.test () 返回的是 char* !所以无法从 int 向 char* 转换!
chinajiji 2003-10-08
  • 打赏
  • 举报
回复
这样就可以了.
char* test(char* p1){
return (char*)(p1-(it->b));
}
这个函数的逻辑通常是错误的.

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧