在 C++ 中处理指向位集的指针

问题描述 投票:0回答:2

我的程序中有一堆 bitsets<32> 作为全局变量,我想在将指向其中一个的指针传递给函数后更新它们。

举个例子:

#include<bits/stdc++.h>
using namespace std; 
bitset<32> zero(0); 
bitset<32> ra(0); 
bitset<32> sp; 
bitset<32> gp; 
bitset<32> tp(0); 
bitset<32> t0(0); 
bitset<32> t1(0); 
void LUI(bitset<32>*rd, int imm){
    bitset<32> temp(imm); 
    for(int i=31; i>=12; i--){
        *rd[i]=temp[i];
    }
    for(int i=11; i>=0; i--){
        *rd[i]=0; 
    }
}

我如何通过函数 LUI() 更新例如 t1,因为取消引用不起作用? 这是我得到的错误:

error: no match for 'operator*' (operand type is 'std::bitset<32>')
   46 |         *rd[i]=0;
 note:   candidate expects 2 arguments, 1 provided
   46 |         *rd[i]=0;
c++ pointers function-definition bitset
2个回答
3
投票

函数

LUI
原样没有意义。我想它只是作为将下标运算符与位集一起使用的示例提供的。不过,您可以通过引用传递给函数位集,而不是通过指针传递它们

void LUI(bitset<32> &rd, int imm);

至于你的问题,而不是

*rd[i]=temp[i];

*rd[i]=0;

你必须写

( *rd )[i]=temp[i];

( *rd )[i]=0;

rd->operator []( i ) = temp[i];
rd->operator []( i ) = 0;

您的代码的问题是下标运算符的优先级高于取消引用运算符。


2
投票

只是详细说明评论和问题的其他答案。

要直接解决您的问题而不进行其他更改,您需要将取消引用括在括号中,如下所示:

(*rd)[i]
。至于为什么需要这样做,归结为运算符优先级(https://en.cppreference.com/w/cpp/language/operator_precedence)在cpp中,[](下标)在*间接(取消引用),在这种情况下,您需要明确地告诉编译器您首先要做什么,否则您将直接在一个只是整数的指针上调用下标运算符。

评论中提出的建议是不要使用。只有当你在做竞争性编程之类的事情时,你才真正想使用它,因为它不是 cpp 标准的一部分;使用它时,不能保证它适用于除 gcc 以外的所有或任何编译器。
另一个问题是包含不必要的标头会减慢编译速度。

个人建议(并在另一个答案中提到)是不要使用指针,而是考虑使用引用而不是指针,这将消除任何运算符优先级问题,同时仍然获得不复制内存的能力。这是带有参考的功能:

void LUI(bitset<32>& rd, int imm) {
    bitset<32> temp(imm); 
    for(int i=31; i>=12; i--){
        rd[i]=temp[i];
    }
    for(int i=11; i>=0; i--){
        rd[i]=0; 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.