如果我有 2 个构造函数重载
calculations(double vector, double angle);
calculations(double horizontalVector, double verticalVector);
如何确保编译器专门使用我选择的重载之一(因为每个重载都在幕后做不同的事情)?
如果我有 2 个构造函数重载
calculations(double vector, double angle);
calculations(double horizontalVector, double verticalVector);
如何确保编译器专门使用我选择的重载之一(因为每个重载都在幕后做不同的事情)?
如果你想要重载,类型需要不同。一种方法是所谓的整体价值习语。
为每个参数制作一个struct
:向量(注意潜在的名称冲突)、角度等。
您将有两个不同的构造函数。
假设您的参数实际上是极坐标和笛卡尔坐标而不是向量,
calculations(double length, double angle);
calculations(double x_coordinate, double y_coordinate);
您可以将它们抽象为类型,
struct Polar { double length, angle; };
struct Cartesian {double x, y; };
和超载
calculations(const Polar& p);
calculations(const Cartesian& c);
接着
calculations c1(Polar{1,1});
calculations c2(Cartesian{1,1});
要提供具有相同参数的不同功能,您可以使用标签调度,您可以在其中提供未使用的参数来进行重载。
struct Calculations {
struct UseTwoVectors {};
Calculations(double vector, double angle);
Calculations(double horizontalVector, double verticalVector, const UseTwoVectors&);
};
int main() {
Calculations c(1, 2);
Calculations d(1, 2, Calculations::UseTwoVectors());
}
总的来说,我不知道这些参数代表什么 - 我怀疑你的代码中的抽象有问题。您可以采用不同的方法并根据您的参数创建一个类。
struct VectorAngle {
double vector, angle;
};
struct TwoVectors {
double horizontalVector, verticalVector;
};
struct Calculations {
Calculations(const VectorAngle& v);
Calculations(const TwoVectors& v);
};
int main() {
Calculations c(VectorAngle{1, 2});
Calculations d(TwoVectors{1, 2});
};