是否有一个库可以检查C++中的变量类型?
Is there a library that check the type of variables in C++?
我有以下类:
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
。
相关文章:
- c++类声明时,相同的例程,不同的成员变量类型
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 创建类似于布尔值的变量类型
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 如何使用变量模板比较 C++ 17 中的变量类型?
- 是否有一个库可以检查C++中的变量类型?
- 与不同变量类型相比,用于变量的 Clang AST 匹配器
- 继承类中的 C++ 成员变量类型重写
- 如何在编译器时动态获取元组内的变量类型C++?
- 在C++中动态分配变量类型
- 用于浮点值的最佳变量类型
- 定义变量类型
- 错误 - 变量类型 "X" 是一个抽象类 - c++
- 在函数 (c++) 中分配变量类型和大小数组
- 具有容器变量类型的类模板
- 获取变量类型名称
- 沿枚举 c++ 返回变量类型
- 是否可以通过模板指定抽象类变量类型
- 什么是变量类型位(32)
- C++ 在知道变量类型之前使用自动定义的变量