是否有一个库可以检查C++中的变量类型?

Is there a library that check the type of variables in C++?

本文关键字:变量 类型 C++ 检查 有一个 是否      更新时间:2023-10-16

我有以下类:

class ComplexNumber
{
public:
ComplexNumber();
ComplexNumber(const float &RealPart, const float &ImaginaryPart);
ComplexNumber(const ComplexNumber &NewComplexNumber);
~ComplexNumber(); // useless
void SetRealPart(const float &RealPart);
void SetImaginaryPart(const float &ImaginaryPart);
friend ComplexNumber operator+(const ComplexNumber &Complex1, const ComplexNumber &Complex2);
friend ComplexNumber operator-(const ComplexNumber &Complex1, const ComplexNumber &Complex2);
friend std::ostream & operator<<(std::ostream &output, const ComplexNumber &NumberToDsiplay);
friend std::istream & operator >>(std::istream &input, ComplexNumber &NumberToInput);
bool operator==(const ComplexNumber &Complex) const;
bool operator!=(const ComplexNumber &Complex) const;
private:
float RealPart;
float ImaginaryPart;
};

我的问题是关于这个运算符重载的:friend std::istream & operator >>(std::istream &input, ComplexNumber &NumberToInput);

以下是实现:

std::istream & operator >>(std::istream &input, ComplexNumber &NumberToInput)
{
std::cout << "Enter the real part: ";
input >> NumberToInput.RealPart;
std::cout << "Enter the imaginary part: ";
input >> NumberToInput.ImaginaryPart;
}

如果我输入string或任何类型的float而不是输入,我会得到一种奇怪的行为。

我该如何处理?

如何使用模板处理它?

如果我输入字符串或任何类型,而不是输入浮点数,我会得到一个奇怪的行为。

您要处理错误的输入:

std::istream& operator>>(std::istream& input, ComplexNumber& NumberToInput)
{
while (std::cout << "Enter the real part: " &&
!(input >> NumberToInput.RealPart))
{
input.clear();
input.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cerr << "Bad input, try again.n";
}
while (std::cout << "Enter the imaginary part: " &&
!(input >> NumberToInput.ImaginaryPart))
{
input.clear();
input.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cerr << "Bad input, try again.n";
}
return input;
} 

如果输入有问题,input.operator>>(std::istream&, float)将返回false,否则true