请查看以下代码
Calculator.h
#pragma once
#include <iostream>
template<class T>
class Calculator
{
public:
Calculator(void);
~Calculator(void);
void add(T x, T y)
{
cout << (x+y) << endl;
}
void min(T x, T y)
{
cout << (x-y) << endl;
}
void max(T x, T y)
{
cout << (x*y) << endl;
}
void dev(T x, T y)
{
cout << (x/y) << endl;
}
};
Main.cpp的
#include "Calculator.h"
using namespace std;
int main()
{
Calculator<double> c;
c.add(23.34,21.56);
system("pause");
return 0;
}
当我运行此代码时,我收到以下错误。我对类模板不熟悉。请帮忙!
1>------ Build started: Project: TemplateCalculator, Configuration: Debug Win32 ------
1>LINK : error LNK2001: unresolved external symbol _mainCRTStartup
1>c:\users\yohan\documents\visual studio 2010\Projects\TemplateCalculator\Debug\TemplateCalculator.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
答案 0 :(得分:0)
很快就把它扔进了VS2010。由于没有使用命名空间std,它不喜欢cout和endl。我只是为速度添加了一个使用声明。我更喜欢正常使用std :: convention,因为这可以避免命名'using'可以生成
的问题它还抱怨没有构造函数和析构函数(在{}中添加)
就像之前的评论所说的那样,将你的主文件放在头文件中也可能不好。这都是test.cpp中的默认项目
编辑我更改了文件结构,将计算器放在.h
中Calculator.h
template<class T>
class Calculator
{
public:
Calculator(void)
{
}
~Calculator(void)
{
}
void add(T x, T y)
{
cout << (x+y) << endl;
}
void min(T x, T y)
{
cout << (x-y) << endl;
}
void max(T x, T y)
{
cout << (x*y) << endl;
}
void dev(T x, T y)
{
cout << (x/y) << endl;
}
private:
T numbers[2];
};
Test.cpp的
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#pragma once
#include <iostream>
using namespace std;
#include "Calculator.h"
int main()
{
Calculator<double> c;
c.add(23.34,21.56);
system("pause");
return 0;
}
答案 1 :(得分:0)
您需要为构造函数和析构函数添加定义
Calculator(void) {}
~Calculator(void) {}
在Calculator.h
中,您需要告诉编译器cout
和endl
来自std
命名空间。例如:
std::cout << (x*y) << std::endl;
答案 2 :(得分:0)
您的项目类型可能有误。 您需要在控制台应用程序中编写此代码。
顺便说一下,还需要考虑其他答案,特别是构造函数和析构函数的定义。