c++ - 指向特定的继承

标签 c++

当我在写我的类(class)时,我发现了一个关于继承的新问题。我的 C++ GCC 编译器(当然还有其他编译器)不知道该怎么做:cast *thisuint32_t然后从 uint32_tmy_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并转换 1uint32_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/

相关文章:

c++ - 指针和引用作为 const 对象的成员变量

c++ - 在 C++ 中初始化字符串

c++ - fstream 保存文件和文件系统交叉链接的文件

c++ - 通过引用将循环计数器或范围声明传递给线程有什么区别?

java - 哪里可以学习JNI函数的用法?

c++ - 在 C++ 中将大于 5 位的数字除以 2 时会失去精度

c++ - 为什么字符串文字是 const?

c++ - 有没有办法知道什么激活了 QAction?

c++ 有没有一种方法可以将优先级队列元素复制到 vector 中,以便可以迭代以检查重复项

python - PyEval_GetLocals 返回全局变量?