在构造函数中设置引用?
Set reference in constructor?
我想用我在构造函数中计算的值设置一个引用。
这可能吗?如何实现?
Class::Class(float data1, float data2, ..) : Superclass(calculatedValue)
{
float calculatedValue = complex calculated from data1, data2, ...
}
//error, because the compiler doesn't know the calculatedValue in the first line.
感谢您的解决方案!
编辑:
如果我使用@dasblinkenlight 的回答,我会得到这个异常:
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll File: c:\program files
(x86)\microsoft visual
studio17\community\vc\tools\msvc.10.25017\include\vector Line:
1754
Expression: vector subscript out of range
For information on how your program can cause an assertion failure,
see the Visual C++ documentation on asserts.
由于 Superclass
采用 float&
,您必须在提供对超类的引用之前为该值分配 space。接下来,您必须在调用 Superclass
构造函数之前将值设置为计算结果。
您可以通过将计算 calculatedValue
的代码放在私有静态成员函数中,并为 float
:
创建一个实例变量来实现
private:
float val;
static float calculateValue(float data1, float data2, ...) {
return complex calculated from data1, data2
}
public:
Class::Class(float data1, float data2, ...)
: Superclass(val = calculateValue(data1, data2, ...)) {
}
现在Superclass
可以设置它对子类val
的引用,它又被设置为对传递给构造函数的参数调用calculateValue
成员函数的结果。
我想用我在构造函数中计算的值设置一个引用。 这可能吗?如何实现?
Class::Class(float data1, float data2, ..) : Superclass(calculatedValue)
{
float calculatedValue = complex calculated from data1, data2, ...
}
//error, because the compiler doesn't know the calculatedValue in the first line.
感谢您的解决方案!
编辑:
如果我使用@dasblinkenlight 的回答,我会得到这个异常:
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll File: c:\program files (x86)\microsoft visual studio17\community\vc\tools\msvc.10.25017\include\vector Line: 1754
Expression: vector subscript out of range
For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.
由于 Superclass
采用 float&
,您必须在提供对超类的引用之前为该值分配 space。接下来,您必须在调用 Superclass
构造函数之前将值设置为计算结果。
您可以通过将计算 calculatedValue
的代码放在私有静态成员函数中,并为 float
:
private:
float val;
static float calculateValue(float data1, float data2, ...) {
return complex calculated from data1, data2
}
public:
Class::Class(float data1, float data2, ...)
: Superclass(val = calculateValue(data1, data2, ...)) {
}
现在Superclass
可以设置它对子类val
的引用,它又被设置为对传递给构造函数的参数调用calculateValue
成员函数的结果。