在Xcode上用c++创建模板类

Creating a template class in C++ on Xcode

本文关键字:建模 创建 c++ Xcode 上用      更新时间:2023-10-16

我应该为分配创建一个模板类,但我得到了很多不同的错误,我真的不明白,有人能帮助我吗?我已经附上了我写的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

类模板称为Initialisedchecker,而不是item。你需要调用对象上的成员函数。你需要:

int main()
{
    Initialisedchecker <int> x;
    x.displayItem();
    // this is strange: x = 5;
    // maybe use:
    // x.setItem( 5 );
    x.displayItem();
}