【发布时间】:2014-04-05 11:25:26
【问题描述】:
我正在创建一个方法,该方法的一个参数要求引用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;
}
现场演示:in here
当我这样做时会发生错误:
void receiver(unsigned int & score = 10u);
编译器返回:
错误:无法将“10u”从“unsigned int”转换为“unsigned int&”
现场演示:in here
【问题讨论】:
-
你不能有引用类型的默认参数,除非它是 const 引用
-
你想要发生什么?你本质上是想说
10 = 100;为什么? -
如果你想要不同的函数做不同的事情,使用重载,而不是默认参数。
-
我冒昧地缩小了标题所暗示的范围……类型兼容性不是这里的问题。