8. Exceptions and files

type conversion

Coercion in C language is not recommended, because any type can be coerced, which may cause many problems, so C++ provides four keywords for type conversion.

  • static_cast<T>(expr)

——Used for conversion between primitive types, but not for conversion between pointers of primitive types

——Used for conversion between class objects with inheritance relationship and conversion between class pointers

 

  • reinterpret_cast<T>(expr)

 - for coercion between pointer types

- for coercion between integer and pointer types

 

  • const_cast<T>(expr)

- used to remove the const attribute of the variable

 

  • dynamic_cast<T>(expr)

——Mainly used for conversion between class hierarchies, and can also be used for cross conversion between classes

#include <iostream>

using namespace std;

class A
{ public:     virtual void show()     { } };



class B : public A
{ public:     virtual void show()     { } };



int main()
{     A a;     B b;     A *pa = &a;     B *pb = &b;     //pa = &b; //The parent class pointer points to the child class object     pa = dynamic_cast<A *>(&b); / /Must have polymorphic attribute     pb = dynamic_cast<B *>(&a); //Can be converted, but there is a problem     return 0; }







    


 

 

abnormal

what is an exception

1) Exception is a program control mechanism, which is independent and complementary to the function mechanism.
     The function is a program control system that connects the upper and lower functions with the stack structure. Exception is another control structure. It is attached to the stack structure, but can be used simultaneously. Set multiple exception types as net capture conditions, so as to jump and return in the stack mechanism with type matching.
2) Exception design purpose: The
    stack mechanism is a highly rhythmic control mechanism, but object-oriented programming requires objects to have direction and presence. The purpose of control drives, from the very beginning, exceptions were to change program control structures to accommodate the subject of object-oriented programs working more efficiently, not just for error handling.
After the exception was designed, it was found that the greatest benefit was obtained in error handling.

Exception Basic Syntax

stack unwind

After the exception is thrown, all objects constructed on the stack during this period will be automatically destructed from the time of entering the try block until the exception is thrown. The order of destruction is the reverse of the order of construction. This process is called unwinding of the stack.
 

exception interface declaration

int Div(int x, int y); //Exception function declaration, can throw any exception
int Div(int x, int y) throw(); //Can't throw any exception
int Div(int x, int y) throw(int, char); //Can throw int and char exceptions

 void func() throw (A, B, C , D); //This function func() can and only throw exceptions of type ABCD and its subtypes .

exception type

1) The exception of throw is of type, which can be used as numbers, strings, and class objects.
2) The exception of throw is typed, and the catch matches strictly according to the type.

 

exception hierarchy

//类的异常
#include <iostream>

using namespace std;

class MyArray
{
private:
	int m_len;
	int *m_data;
public:
	MyArray(int l);
	~MyArray();
	int &operator [](int index)
	{
		return m_data[index];
	}
	int GetLength()
	{
		return m_len;
	}
	
	class eSize
	{
	protected:
		const char *ErrMsg;
	public:
		eSize(char *msg) : ErrMsg(msg)
		{}
		virtual void printErr() = 0;
	};
	class eNegative : public eSize
	{
	public:
		eNegative() : eSize("Negative exception")
		{}
		void printErr()
		{
			cout << ErrMsg << endl;
		}
	};
	class eZero : public eSize
	{
	public:
		eZero() : eSize("Zero exception")
		{}
		void printErr()
		{
			cout << ErrMsg << endl;
		}
	};
	class eTooSmall : public eSize
	{
	public:
		eTooSmall() : eSize("TooSmall exception")
		{}
		void printErr()
		{
			cout << ErrMsg << endl;
		}
	};
	class eTooBig : public eSize
	{
	public:
		eTooBig() : eSize("TooBig exception")
		{}
		void printErr()
		{
			cout << ErrMsg << endl;
		}
	};
};

MyArray::MyArray(int l)
{
	m_len = l;
	if(m_len < 0)
	{
		throw eNegative();
	}
	else if(m_len == 0)
	{
		throw eZero();
	}
	else if(m_len > 0 && m_len <= 10)
	{
		throw eTooSmall();
	}
	else if(m_len > 1000)
	{
		throw eTooBig();
	}
	m_data = new int[m_len];
}

MyArray::~MyArray()
{
	if(m_data != NULL)
	{
		delete[] m_data;
	}
}

int main()
{
	try
	{
		MyArray a(20);
		for (int i = 0; i < a.GetLength(); i++)
		{
			a[i] = i;
		}
	}
	
	catch(MyArray::eNegative &e)
	{
		e.printErr();
	}
	catch(MyArray::eZero &e)
	{
		e.printErr();
	}
	catch(MyArray::eTooSmall &e)
	{
		e.printErr();
	}
	catch(MyArray::eTooBig &e)
	{
		e.printErr();
	}
	
	return 0;
}

 

c++ input and output streams

The input of the program refers to the transfer of data from the input file to the program, and the output of the program refers to the transfer of data from the program to the output file.
C++ input and output include the following three aspects:
    input and output to the standard equipment specified by the system. That is, data is input from the keyboard and output to the monitor screen. This input and output is called standard input and output, or standard I/O for short.
    Input and output with external storage disk files as objects, that is, input data from disk files, and output data to disk files. The input and output of the external storage file as the object is called the input and output of the file, abbreviated as file I/O.
    Perform input and output to the specified space in memory. Usually a character array is specified as storage space (which can actually be used to store any information). This input and output is called string input and output, or string I/O for short.

 

Common input and output stream header files

  • iostream contains the basic information needed to operate on input and output streams.
  • fstream is used for I/O operations on user-managed files.
  • strstream is used for string stream I/O.
  • stdiostream is used when mixing C and C++ I/O mechanisms, for example when wanting to convert a C program to a C++ program.
  • iomanip should include this header when using formatted I/O.

 

Standard I/O stream

Standard I/O objects: cin, cout, cerr, clog

Standard input stream object cin, the key function
      cin.get() //can only read one character at a time encounter EOF end
      cin.get(one parameter) //read one character
      cin.get(three parameters) // Can read strings cin.getline(
      ) cin.ignore(
      )
      cin.peek()
      cin.putback()

Standard output stream object cout
      cout.flush()
      cout.put()
      cout.write()
      cout.width()
      cout.fill()
      cout.setf(marker)
 
manipulator(operator, control character)
flush
endl
oct
dec
hex
setbase
setw
setfill
setprecision
 

file I/O

The input and output classes related to the file are mainly defined in the header file fstream.h. Three classes are mainly defined in this header file. These three classes control various input and output operations on the file. They are respectively Is ifstream, ofstream, fstream, where the fstream class is derived from the iostream class

file read and write

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ofstream ofs("world.txt", ios::app);
	char buf[32] = {0};

	ifstream ifs("hello.txt", ios::in);
	ifs >> buf;
	ofs << buf;

	return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324358784&siteId=291194637