gpt4 book ai didi

c++ - C++ 上奇怪的隐式转换

转载 作者:行者123 更新时间:2023-11-28 02:34:37 25 4
gpt4 key购买 nike

我有一个关于意外转换的问题:

class BadString
{
public:
BadString(char const*);
...
char& operator[] (size_t); //(1)
char const& operator[] (size_t);

operator char* (); //(2)
operator char const* ();

};

int main()
{
BadString str("correkt");
str[5] = 'c'; //possibly an overload resolution ambiguity !!!
}

解释是这样的:

The subscript operator at (1) seems like a perfect match. However is not quite perfect because the argument 5 has type int, and the operator expects size_t (unsigned int or unsigned long, but never int). Still, a simple standard integer conversion makes (1) easily viable. However, there is another candidate: the built-in subscript operator. Indeed, if we apply the conversion operator (2) to str, we obtain a pointer type, and now the the built-in subscript operator applies. This operator takes a ptrdiff_t argument, which on many platforms is equivalent to int.

我理解为 (1) 的原始参数不匹配,然后会发生隐式转换,但我不明白为什么编译器会尝试使用 (2) 转换 str。

谢谢。

最佳答案

如果我像这样“扩展”您的代码并将第二个下标运算符方法设为常量,那么结果将是

#include <iostream>
#include <cstring>

class BadString {
public:
char s[1024];
BadString(const char* s_) {
strncpy(s, s_, strlen(s_) + 1);
}
char& operator[](size_t pos) {
return s[pos];
}
const char& operator[](size_t pos) const {
return s[pos];
}

operator char*() {
std::cout << "operator char*\n";
}

operator const char*() {
std::cout << "operator const char*\n";
}
};

int main() {
BadString bs("correkt");
bs[5] = 'c';
std::cout << bs.s << "\n";
}

然后编译运行,结果如预期,输出只有一行

correct

发生 (2) 隐式转换运算符等事实意味着您没有提供有关 BadString 类的完整信息。也许你应该这样做。

当然,如果它像提供的示例中那样实现,则没有任何理由调用 (2) 隐式转换运算符。

UPD: 考虑到您在评论中提到的内容,我想目的是operator const char*() 就是这样的显式转换

(const char*)bs

返回指向数组 s 的第一个元素的指针,bs 正在保存。也就是说,当然,不正确,有点难看,但这是我看到的唯一选择。

关于c++ - C++ 上奇怪的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27945298/

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