【发布时间】:2015-08-01 14:45:30
【问题描述】:
我知道这个问题被问了很多,但我来自 Java,很长时间没有做过任何 C/C++。
你能提醒我如何在 C++ 中正确地将一个对象传递给另一个对象的构造函数吗?
例如,我需要将一个新的 Light 对象传递给 Button 构造函数:
// LED Light
class Light {
int pin;
public:
Light(int p) {
pin = p;
}
};
// BUTTON
class Button {
Light ledLight;
public:
Button(Light l) {
ledLight = l;
}
};
Light my_led(0);
Button my_button(my_led);
这就是我在类似 Java 的方式中的做法。 但是,这会产生以下错误:
:: In constructor ‘Button::Button(Light)’:
:: 16:19: error: no matching function for call to ‘Light::Light()’
:: 16:19: note: candidates are:
:: 6:3: note: Light::Light(int)
:: 6:3: note: candidate expects 1 argument, 0 provided
:: 2:7: note: Light::Light(const Light&)
:: 2:7: note: candidate expects 1 argument, 0 provided
对象是通过引用传递还是在我创建新按钮时尝试创建新对象?
或者我需要在Button的构造函数中将Light声明为指针吗?
非常感谢任何帮助!
【问题讨论】:
-
现在写100次:“C is not C++ is not C!”
-
另外值得注意的是,与 Java 不同,对
my_button.ledLight的更改不会更改my_led的内容。您复制了对象。 -
@Olaf,我真的很抱歉,特别是惭愧,因为我自己经常要求人们用“Java/JavaScript”做同样的事情。感谢您的编辑。 @BillLynch,我如何将
my_led直接传递给my_button?这样按钮的更改会影响其内容。 -
@YemSalat 您可以将
ledlight设为参考 -
@awesomeyi,喜欢这样吗?
Light& ledLight;然后:Button(Light& l) { }在构造函数声明中?
标签: c++ constructor pass-by-reference