I wrote a simple template class, which works fine, if the objects are created without using pointers. However if I need to create a pointer to that class object, I get error: invalid conversion from 'int' to 'Logger<int>*' [-fpermissive]
. I am attaching the code below. Any help is appreciated. Thank you.
#include <iostream>
using namespace std;
template<typename T>
class Logger
{
public:
Logger (const T& d) {data = d;}
void print(){std::cout << "data: " << data << std::endl;}
private:
int data;
};
int main() {
/*
// Works
Logger<int> myLogger(5);
myLogger.print();
*/
Logger<int>* myLogger(5);
myLogger->print();
return 0;
}
If you wanted to allocate a pointer you'd need to use new
(and remember to delete
it when it is no longer needed so you don't leak it).
Logger<int>* myLogger = new Logger<int>(5);
I don't know what your use case is for doing this, but if you really need to dynamically allocate the object, I'd recommend using smart pointers if you can.
std::unique_ptr<Logger<int>> myLogger = std::make_unique<Logger<int>>(5);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.