在 Xcode 上用 C++ 创建模板 class
Creating a template class in C++ on Xcode
我应该为作业创建一个模板 class,但我遇到了很多我不太理解的不同错误,有人可以帮助我吗?我附上了我写的cp和头文件。我知道这可能很简单,但我是新手,谢谢!
#ifndef __Template_example__Initialisedchecker__
#define __Template_example__Initialisedchecker__
#include <stdio.h>
template <class data>
class Initialisedchecker
{
private:
data item;
bool definedOrN;
public:
Initialisedchecker()
{
definedOrN = false;
}
void setItem(const data&)
{
std::cin >> item;
definedOrN = true;
}
void displayItem()
{
if (definedOrN)
{
std::cout << item;
}
else
{
std::cout << "error, your item is undefined";
}
}
};
#endif
这是主要的:
#include <iostream>
#include "Initialisedchecker.h"
using namespace std;
int main()
{
item <int> x;
displayItem();
x = 5;
displayItem();
}
抱歉,我忘记添加我遇到的错误,头文件没有给出任何错误,但主要是说:
Use of undeclared identifier 'display item' ,
Use of undeclared identifier 'item' ,
Use of undeclared identifier 'x' ,
Expected a '(' for function-style cast or type construction
class 模板称为 Initialisedchecker
,而不是 item
。你需要调用对象的成员函数。您需要:
int main()
{
Initialisedchecker <int> x;
x.displayItem();
// this is strange: x = 5;
// maybe use:
// x.setItem( 5 );
x.displayItem();
}
我应该为作业创建一个模板 class,但我遇到了很多我不太理解的不同错误,有人可以帮助我吗?我附上了我写的cp和头文件。我知道这可能很简单,但我是新手,谢谢!
#ifndef __Template_example__Initialisedchecker__
#define __Template_example__Initialisedchecker__
#include <stdio.h>
template <class data>
class Initialisedchecker
{
private:
data item;
bool definedOrN;
public:
Initialisedchecker()
{
definedOrN = false;
}
void setItem(const data&)
{
std::cin >> item;
definedOrN = true;
}
void displayItem()
{
if (definedOrN)
{
std::cout << item;
}
else
{
std::cout << "error, your item is undefined";
}
}
};
#endif
这是主要的:
#include <iostream>
#include "Initialisedchecker.h"
using namespace std;
int main()
{
item <int> x;
displayItem();
x = 5;
displayItem();
}
抱歉,我忘记添加我遇到的错误,头文件没有给出任何错误,但主要是说:
Use of undeclared identifier 'display item' ,
Use of undeclared identifier 'item' ,
Use of undeclared identifier 'x' ,
Expected a '(' for function-style cast or type construction
class 模板称为 Initialisedchecker
,而不是 item
。你需要调用对象的成员函数。您需要:
int main()
{
Initialisedchecker <int> x;
x.displayItem();
// this is strange: x = 5;
// maybe use:
// x.setItem( 5 );
x.displayItem();
}