无法从"无符号 int"转换为"无符号 int&"
could not convert from 'unsigned int' to 'unsigned int&'
我正在创建一个方法,该方法的一个参数要求引用unsigned int
,但我想为该参数设置一个默认值。例如:
#include <iostream>
using namespace std;
class A {
public:
void sender();
private:
unsigned int score = 10;
};
class B {
public:
void receiver(unsigned int & score);
};
void A::sender() {
cout << "Before: " << score << endl;
B b;
b.receiver(score);
cout << "After: " << score << endl;
}
void B::receiver(unsigned int & score) {
score = 100;
}
int main() {
A a;
a.sender();
return 0;
}
现场演示:在这里
错误发生在我这样做的时候:
void receiver(unsigned int & score = 10u);
编译器返回:
错误:无法将"10u"从"unsigned int"转换为"unsignedint&">
现场演示:在这里
不能将文本1分配给非const
引用。
有两种情况适合您的情况:
您打算修改传递给receiver()
的参数
如果是这种情况,则使用不带默认参数的非常量引用(unsigned int & score
)。在将文字或临时对象传递给它的情况下,它将导致编译器错误。
a.receiver(10); // Error
考虑到您想要修改该参数,以上内容没有任何意义(如果C++允许2,则不会看到修改)。
您只想以只读方式使用该参数
只需使用普通的、非引用的unsigned int
,因为const unsigned int& score
写起来很痛苦。如果您确定一个对象的复制成本很高,那么此时您应该将参数作为常量引用。
更新:有些情况下,您想要修改某些内容,但某些内容可能存在,也可能不存在。在这种情况下,您可能需要使用非拥有的指针作为参数。
// Declaration
void receiver(unsigned int* score = nullptr);
void B::receiver(unsigned int* score) {
if(score) *score = 100;
}
...
a.receiver(); // Uses the default parameter
unsigned int x;
a.reciever(&x);
在这种情况下,它只在指向某个(假定的)有效变量时分配给score
。指针一点也不坏。
更新2:然而,正如@Potatoswatter所指出的,函数重载可能会让你过得更好。
void B::receiver() {
// Do something else
}
void B::receiver(unsigned int& score) {
score = 100;
}
您应该在希望重载在不同参数上表现不同的情况下使用此选项。
然而,我更喜欢第一个非默认参数选项,而不是指针选项和重载选项,因为它要求调用方提供一个参数,当您通过函数修改某些内容时,这会更好。
UPDATE 3:您还应该考虑让函数返回值,而不是通过参数来修改它。在不需要修改对象的当前状态的情况下,让函数返回值会更直观。不过,有一点需要注意,调用者可能会忘记捕获(分配)返回值,如果您将该值用作某个资源ID来释放某些内容,这可能会很危险。
1一般来说,是一个临时对象。
2如果10神奇地变成100,宇宙可能会爆炸;)
您希望参数类型为const unsigned int&
。否则,你可以做一些疯狂的事情,比如尝试分配10 = 20
,这是没有意义的。
而你恰好就是这么做的。score = 100
行似乎并不是你真正的意思。
值"10"不是引用,而是一个值。通过具有By-reference参数,必须使用引用来调用它。使用默认参数意味着您可以在不指定参数的情况下调用函数,编译器将使用默认参数。
类似地,调用b.receiver(10);
是无效的,但是
int someInt = 10;
b.receiver(someInt);
有效。
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 从 std::vector<无符号字符>切片中提取 int?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- C++无符号短裤的划分导致 int
- 将无符号转换为复杂<int>原因符号转换警告
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- 无符号的 int 到有效数字
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 有没有办法在C++中将mpz_t转换为 int 或无符号长 int?
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 为什么QByteArray的大小是"int"而不是"无符号int"
- 为什么 (-i) 的类型(其中 i 是无符号的 int)仍然是无符号的 int?
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 如何对无符号长 int 进行位掩码?
- 使用无符号int作为二进制来在c++中实现一个集
- 这个右移是如何工作的:字符串流>>无符号的int>>无符号的int?
- 转换 int -> 无符号长 长 是否由标准定义
- 为什么在执行 int / 无符号 int 除法时使用 'divl'