这是一个基本程序,用于获取两个 5 位数字作为字符串,并利用对 '+' 的运算符重载对这 2 个数字进行加法。
#include <iostream>
#include <limits>
#include <cstdlib>
#include <cstring>
#include <sstream>
using namespace std;
class IntStr
{
int InputNum;
public:
//IntStr();
IntStr::IntStr(int num);
IntStr operator+ (const IntStr &);
//~IntStr();
void Display();
};
IntStr::IntStr(int num)
{
InputNum = num;
}
void IntStr::Display()
{
cout << "Number is (via Display) : " << InputNum <<endl;
}
IntStr IntStr::operator+ (const IntStr & second) {
int add_result = InputNum + second.InputNum;
return IntStr(add_result);
}
int main()
{
string str;
bool option = true;
bool option2 = true;
while (option)
{
cout << "Enter the number : " ;
if (!getline(cin, str))
{
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss)
{
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
}
else if (i < 10000 || i > 99999)
{
cerr << "Out of range!\n";
}
else
{
// Process i
//cout << "Stream is: " << iss << endl; //For debugging purposesc only
cout << "Number is : " << i << endl;
option = false;
IntStr obj1 = IntStr(i);
obj1.Display();
}
}//while
while (option2)
{
cout << "Enter the second number : " ;
if (!getline(cin, str))
{
cerr << "Something went seriously wrong...\n";
}
istringstream iss(str);
int i;
iss >> i; // Extract an integer value from the stream that wraps str
if (!iss) //------------------------------------------> (i)
{
// Extraction failed (or a more serious problem like EOF reached)
cerr << "Enter a number dammit!\n";
}
else if (i < 10000 || i > 99999)
{
cerr << "Out of range!\n";
}
else
{
// Process i
//cout << "Stream is: " << iss << endl; //For debugging purposes only
cout << "Number is : " << i << endl;
option2 = false;
IntStr obj2 = IntStr(i);
obj2.Display();
//obj1->Display();
}
}//while
//IntStr Result = obj1 + obj2; // --------------------> (ii)
//Result.Display();
cin.get();
}
需要澄清上述代码中的 (i) 和 (ii) 点......
(1) (i) 实际上做了什么?
(2) (ii) -> 不编译.. 出现错误“obj1 not declared (first use this function)”。这是因为 obj1 和 obj2 仅在 while 循环内声明吗?我如何在全局范围内访问它们?
最佳答案
1) 来自 http://www.cplusplus.com/reference/iostream/ios/operatornot/ :
bool operator ! ( ) const; Evaluate stream object
Returns true if either one of the error flags (failbit or badbit) is set on the stream. Otherwise it returns false.
来自 http://www.cplusplus.com/reference/iostream/ios/fail/ :
failbit is generally set by an input operation when the error was related with the internal logic of the operation itself, while badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is performed on the stream.
2) 这两个对象不在范围内,它们只存在于前面的括号中。
关于c++ - (C++ 查询)全局访问实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/767375/