绑定到函数的指针只能用于调用函数
我刚刚从 char 数组转移到 std::string 并且已经遇到了问题,我可能正在做一些非常愚蠢的事情,请随意嘲笑:
int main()
{
string * p = new string;
memset(p, 0, sizeof(string));
expected_exepath(p);
cout << p->data;
delete p;
}
错误在 p->data 中,其中显示“绑定到函数的指针只能用于调用函数”.. p 是 std::string,所以我不明白为什么它认为我正在尝试调用函数。
I've just moved from char arrays to std::string and I've already ran into a problem, I'm probably doing something extremely stupid, feel free to ridicule:
int main()
{
string * p = new string;
memset(p, 0, sizeof(string));
expected_exepath(p);
cout << p->data;
delete p;
}
The error is in p->data, which says "a pointer bound to a function may only be used to call a function".. p is std::string, so I don't see why it thinks I'm trying to call a function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为数据是一个函数,而不是数据成员。更重要的是,
std::string
的一半意义在于它是一个值。你不应该使用new
,除非你有一个非常充分的理由——在堆栈上分配,或者如果你必须动态分配使用容器或智能指针。另外:永远、永远、永远不要像这样 memset UDT。他们始终照顾自己的内部状态,并且不会扰乱它。
Because data is a function, not a data member. More importantly, half the point of
std::string
is that it's a value. You shouldn't usenew
unless you have an extremely good reason- allocate on the stack, or if you must dynamically allocate use a container or smart pointer.Also: Do not ever, ever, ever memset UDTs like that. They take care of their own internal state, all the time, and do not mess with it.
几点:
string::data()
是一个函数,因此该错误消息是完全合适的。p
是指向std::string
的指针,而不是std::string
。< /p>将
p->data()
传递给cout
会很危险,因为data()
返回一个没有 null 终止符的 char 数组,与string::c_str()
不同。我建议你只使用<前><代码>cout << *p;
...相反。
如果
expected_exepath
接受std::string*
参数,那么我建议像这样重写你的函数:A few points:
string::data()
is a function, hence that error message is entirely appropriate.p
is a pointer to astd::string
, not anstd::string
.Passing
p->data()
tocout
would be dangerous given thatdata()
returns a char array without a null terminator, unlikestring::c_str()
. I'd suggest you just use...instead.
If
expected_exepath
takes astd::string*
argument, then I'd suggest re-writing your function like this:string::data()
是一个函数,而不是数据成员。您需要调用它,而不仅仅是取消引用它。像这样:string::data()
is a function, not a data member. You need to call it, not just dereference it. Like this:我想提供另一个可能的错误,该错误会导致相同的错误消息,尽管与您的具体问题无关。
当您使用
vector.emplace_back{.. , ..}
而不是vector.emplace_back(.. , ..)
时。希望像我这样犯这个错误的人不会困惑几个小时。
I'd like to provide another possible mistake that cause the same error message although not related to your specific question.
It's when you use
vector.emplace_back{.. , ..}
instead ofvector.emplace_back(.. , ..)
.Hope maybe someone making this mistake like me does not get confused for hours.