c++ Write a simple templated dummy class MyTemplate Give it some functionality,
ID: 3744791 • Letter: C
Question
c++
Write a simple templated dummy class MyTemplate Give it some functionality, e.g: - a parameterized constructor that initializes some private data member my_data_ of type ItemType - an accessor member function getData() Write a main() function that initializes different MyTemplate objects with different types (e.g. int, string) and makes calls to their accessor member functions to observe their behavior. E.g: MyTemplate intObject; cout << intObject.getData() << endl; Make sure you understand and don’t have problems with multi-file compilation using templates
Here are my files. However, they do not compile properly and show errors. Please fix these files and the proper command that is used to compile templates. These files are needed as the instructions say but please fix the content and my file structures. THank you
INTERFACE TEMP.H file
#include <iostream>
#ifndef TEMP_H_
#define TEMP_H_
#include <string>
using namespace std;
template <typename ItemType>
class MyTemplate {
private:
ItemType my_data_;
public:
MyTemplate(ItemType data);
// my_data_ = data;
ItemType getData();
};
#endif //BAG_H_
temp.cpp file
#include "temp.h"
template <typename ItemType>
MyTemplate::MyTemplate(ItemType data){
my_data_ = data;
}
template <typename ItemType>
ItemType MyTemplate::getData() {
return my_data_;
}
main.cpp file
#include <iostream>
#include "temp.h"
using namespace std;
int main() {
MyTemplate<int> intObject(5);
cout << intObject.getData() << endl;
MyTemplate<string> stringObject("hello");
cout << stringObject.getData() << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
template <typename ItemType>
class MyTemplate {
private:
ItemType my_data_;
public:
MyTemplate(ItemType data) {
my_data_ = data;
}
ItemType getData() {
return my_data_;
}
};
int main() {
MyTemplate<int> intObject(5);
cout << intObject.getData() << endl;
MyTemplate<string> stringObject("hello");
cout << stringObject.getData() << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.