c ++ compiler error error LNK2001: unresolved external symbol

c ++ compiler error error LNK2001: unresolved external symbol

This error is really confusing, usually prompted to unresolved a function or a variable.
If it is variable, generally static member variables static typename xxxwithout initialization will use (if data are not members of the class vs will complain).
The reason is that if we just declare a static variable without initialization , then the compiler is not a static variable for the allocation of space , only when the initialization of static variables after the compiler will give this variable is assigned a static area of memory space , so that the program to find this variable in the data area and continue to use.
If it is a function, the situation I encountered at present are:
1) only declared the function, but did not complete the definition;
2) met today, call the derived class, the base class with no virtual functions complete the definition of life.

//Declaration.h
class myExc 
	{
	protected:
		double a;
		double b;
	public:
		myExc() :logic_error(""){}
		virtual void show();
	};
	
	class bad_gmean :myExc
	{
	public:
		bad_gmean(){}
		void show(){ cout << "gmean( " << a << " , " << b << " ): invalid arguments: a < 0 or b < 0\n"; }
	};

	class bad_hmean :myExc
	{
	public:
		bad_hmean(){}
		void show(){ cout << "hmean( " << a << " , " << b << " ): invalid arguments: a = -b\n"; }
	};

The figure can be seen that a derived class overrides the base class void show()function, but the base class void show()is not defined inline.

//main.cpp
/*
...
*/
catch (myExc &b)
		{
			b.show();
			cout << "Exception type: " << typeid(b).name() << endl;
			cout << "Try again.\n";
			continue;
		}
/*
...
*/
		

The figure can be seen that the main function, we have to call the derived class by way of reference to the base class show()function , although not directly use the base class show(), however, use the base class reference in the derived class to call a function of the way belongs to the dynamic binding , is complete when the program is running, and in the compilation phase of the program , the compiler still think there call the base class show()function , and therefore error.
Modifications is very simple, to ensure that no call to the base class methods premise , the direct inline function defines the base class show():

virtual void show() {}

Or pure virtual function is a function, the corresponding base class will be transformed into an abstract base class:

virtual void show() = 0

To use the base class show complete other operations, you have to show a corresponding function in the base class definition.

Published 16 original articles · won praise 10 · views 4924

Guess you like

Origin blog.csdn.net/weixin_44826484/article/details/104300070