我正在尝试学习新的 C++ 标准,但在使用智能指针时我遇到了不足。
这是我正在编写的一个不想运行的程序的代码:
#include <iostream>
#include <memory>
template <typename T> class printer
{
public:
printer(T val)
{
value = val;
}
void printvalue()
{
std::cout << "The value is " << val;
std::cin.get();
}
private:
T value;
};
template <typename T> class test
{
public:
test(T value)
{
printer<T> * test = new printer<T>(value);
*printValue = test;
}
void beginTest()
{
printValue.get()->printvalue();
}
private:
std::unique_ptr<printer<T>> printValue;
};
我这样写了main函数:
int main()
{
test<int> t(5);
t.beginTest();
return 0;
}
编译后出现以下错误:
二进制“=”:找不到采用“printer *”类型右侧操作数的运算符(或者没有可接受的转换)
this 指的是这行代码:
*打印值=测试;
我认为 new 即使在这种情况下也应该可以工作,不,我可以超载我想的运算符,但我确信我缺少一些东西
注意:我使用的是Visual Studio 2013编译器
请帮忙
您可以直接将指针传递给std::unique_ptr
构造函数:
test(T value)
: printValue(new printer<T>(value))
{ }
或者您可以致电reset
on the std::unique_ptr
:
test(T value)
{
printValue.reset(new printer<T>(value));
}
请注意,您不需要使用get()
访问该对象unique_ptr
指向 - 你可以像对待普通指针一样对待它:
printValue->printvalue();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)