我有一个关于显式和模板的问题:
template<class T>
class A {
class A_Impl {
T var;
public:
explicit A_Impl(T var1) : var(var1), version(1)
{
}
A_Impl(const A_Impl& a ) : var(a.var), version(1)
{
}
const A_Impl& operator=(const A_Impl& a)
{
var=a.var;++version;return *this;
}
operator T() const { return var; }
friend class A<T>;
};
A_Impl a;
public:
A(T var): a(var)
{
}
A_Impl& get() { return a; }
};
void main() {
A<int> a1(5);
cout<<"a1 = "<<a1.get()<<endl;
a1.get()=7;
cout<<"a1 = "<<a1.get()<<endl;
a1=13;
cout<<"a1 = "<<a1.get()<<endl;
}
我在 a1.get()=7;
处遇到错误,表示没有运算符“=”匹配这些操作数
此外,如果我明确指出它会编译,但我不明白 a1.get()
函数和 a1=13;
之间的区别即使有显式也很好。
最佳答案
I get en error at a1.get()=7; which says no operator "=" matches these operands
对于 operator=
,无法将 7
转换为 A_Impl
,因为构造函数 A_Impl(T)
,在此实例中扩展为 A_Impl(int)
,声明为 explicit
。
您可以删除 explicit
关键字,或者显式创建一个 A_Impl
:
a1.get() = A_Impl(7);
或者你也可以声明一个特定的operator=
:
const A_Impl& operator=(const T&)
对于 A_Impl
类。
Also, if i take explicit word out it will compile, but i dont understand the difference between the a1.get() function and a1=13; which works fine even with explicit.
a1 = 13
工作正常,因为模板类 A
有一个 非显式 构造函数到 T
(特别是 A(T var)
),在这种情况下,它与 T = int
完美匹配。
另请注意,main
应始终返回 int
,而不是 void
。
关于c++ - 显式使用模板,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21204277/