当我在写我的类(class)时,我发现了一个关于继承的新问题。我的 C++ GCC 编译器(当然还有其他编译器)不知道该怎么做:cast *this
至 uint32_t
然后从 uint32_t
至 my_class
, 或者只使用 my_class operator<<
重载。 我希望编译器始终将第二个变量与 my_class
一起使用.
说实话,我不知道怎么解决这个问题。我需要一些特殊的关键字吗?
具有相同问题的简单示例:
#include <iostream>
#include <bitset>
class my_class
{
public:
std::bitset<32> _data;
my_class(const std::bitset<32>& x) : _data(x) {}
my_class(const uint32_t x) : _data(x) {}
operator uint32_t() const {
return _data.to_ulong();
}
my_class operator<< (uint32_t pos) const {
return my_class(_data << pos);
}
my_class foo() const {
// Some code...
my_class tmp = (*this << 1); // This line produces warnings
// ...
return tmp;
}
};
int main()
{
auto entity = my_class(42);
entity.foo();
}
编译器警告:
source_file.cpp: In member function ‘my_class my_class::foo() const’:
source_file.cpp:25:34: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
my_class tmp = (*this << 1); // This line produces warnings
^
source_file.cpp:19:14: note: candidate 1: my_class my_class::operator<<(uint32_t) const
my_class operator<< (uint32_t pos) const {
^
source_file.cpp:25:34: note: candidate 2: operator<<(uint32_t {aka unsigned int}, int) <built-in>
my_class tmp = (*this << 1); // This line produces warnings
最佳答案
这就是应该避免隐式转换的原因。当你这样做的时候
*this << 1
您可以调用 operator uint32_t() const
然后换档,或调用my_class operator<< (uint32_t pos) const
并转换 1
到 uint32_t
.无论哪种方式,都存在转换,因此两者成为平等匹配,因此存在歧义。
有几种方法可以修复它。首先,只需将转换运算符标记为 explicit
.使用
explicit operator uint32_t() const {
return _data.to_ulong();
}
允许代码编译,因为它强制它使用你重载的 operator <<
.您也可以切换到使用 _data
直接点赞
my_class tmp = (_data << 1);
这也将编译。
关于c++ - 指向特定的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57559669/