且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++错误:函数“int_cdecl invoke_main(void)”中引用的未解析的外部符号_main

更新时间:2023-02-19 21:18:35

你的主要不应该是模板,这是你当前的错误。您在上面评论的错误(在评论部分中)告诉您编译器没有看到模板实例的实现,这可能是因为您将该代码放在cpp文件而不是标题中。



以下是此问题的一些参考链接:

c ++ - 为什么模板只能在头文件中实现? - 堆栈溢出 [ ^ ]

c ++模板和头文件 - Stack Overflow [ ^ ]

When I compile this code it gives me this error :
Unresolved external symbol _main referenced in function "int_cdecl invoke_main(void)"
what's the problem with my code?

What I have tried:

main function :

#include "stdafx.h"
#include <iostream>
#include "myqueue.h"
using namespace std;
template <class T>
int main()
{
	myqueue <int> intQueue;
	cout <<"size ="<< intQueue.size() << endl;
	intQueue.add(10);
	intQueue.add(20);
	intQueue.add(30);
	cout << intQueue.retrieve() << endl;
	intQueue.remove();
	intQueue.add(40);
	intQueue.add(50);
	cout << intQueue.retrieve() << endl;
	intQueue.remove();
	intQueue.add(60);
	cout <<"size ="<< intQueue.size() << endl;
	while
		(!intQueue.isEmpty())
	{
		cout << intQueue.retrieve() << endl;
		intQueue.remove();
	}
	cout <<"size ="<< intQueue.size() << endl;
	return 0;
   
}




myqueue.h:

#include<stack>
using namespace std;
template <class T>
class myqueue
{
private:stack <T> st1, st2;
public:
	myqueue();
	~myqueue();
	bool add(T element);
	T retrieve();
	bool remove();
	bool isEmpty();
	int size();
};



myqueue.cpp:

#include "stdafx.h"
#include "myqueue.h"
#include <stack>
using namespace std; 

template <class T>
myqueue<T>::myqueue()
{
}
template <class T>
myqueue<T>::~myqueue()
{
}
template <class T>
bool myqueue<T>::add(T element) {
	st1.push(element);
	return true;
}
template <class T>
bool myqueue<T>::isEmpty() {
	if (st1.size()== 0) {
		cout << "Empty queue" << endl;
		return true;
	}
	cout << "Not empty queue" << endl;
	return false;
}
template <class T>
int myqueue<T>::size() {
	return st1.size();
}
template <class T>
T myqueue<T>::retrieve() {
	while (!st1.empty) {
		st2.push(st1.top);
		st1.pop();
	}
	T item = st2.top();
	while (!st2.empty) {
		st1.push(st2.top());
		st2.pop();
	}
	return item;
}
template <class T>
bool myqueue<T>::remove() {
	if (!st1.empty) {
		while (!st1.empty) {
			st2.push(st1.top);
			st1.pop();
		}

		while (!st2.empty) {
			st1.push(st2.top());
			st2.pop();
		}
		return true;
	}
	else return false;
}

Your main shouldn't be a template, that's your current error. The error you commented on above (in comments section) is telling you that the compiler doesn't see the implementations for the template instance, this is probably because you put that code in a cpp file instead of the header.

Here are some reference links to this issue:
c++ - Why can templates only be implemented in the header file? - Stack Overflow[^]
c++ template and header files - Stack Overflow[^]