对于C++我很陌生,我想知道是否有任何方法可以重复构造函数,并且传递参数的变体。 我需要确定正确的给定值(float或int),检查float是否可以很好地转换为整数(例如1.0),并调用另一个构造函数,如果我的值通过测试,则接受两个整数。在C++中用于不同参数的多个构造函数
如果任何人有任何关于改进这个解决方案的提示,那一般会很棒。
Fraction(int n, int d) : numerator(n), denominator(d) {
simplify(n, d);
}
Fraction(float n, float d) {
if (!isInteger(n) && !isInteger(d)) {
throw invalid_argument("Fractions only accept real numbers.");
} else {
Fraction(int(n), int(d));
}
}
Fraction(int n, float d) {
if (!isInteger(n) && !isInteger(d)) {
throw invalid_argument("Fractions only accept real numbers.");
} else {
Fraction(int(n), int(d));
}
}
Fraction(float n, int d) {
if (!isInteger(n) && !isInteger(d)) {
throw invalid_argument("Fractions only accept real numbers.");
} else {
Fraction(int(n), int(d));
}
}
如果您的编译器支持它们,委托构造函数。 – user657267 2014-10-27 22:22:26
如果你只想支持整数值,为什么你想要一个选项,需要'浮动'? – 2014-10-27 22:22:49
你的逻辑对条件是错误的。另外,你为什么要检查参数是整数?编译器应该已经这样做了。添加无用的消息,并抛出异常只会让你的代码更长。 – 2014-10-27 22:26:48