如下面的这段代码所示,模板类里面有一个模板成员函数,其中有问题的地方我已经标注了,就是注释的那一行。请问为什么要用getValue()这个成员函数啊,如果没有main函数里面的语句,用x.value()是可以编译通过的,但是因为有了main()里面的语句,就必须要用个成员函数才行,这是为什么啊?
#include <iostream>
template<typename T>
class MyClass
{
private:
T value;
public:
/*void assign(const MyClass<T>& x)
{
value = x.value;
}*/
template <typename X>
void assign(const MyClass<X>& x)
{
value = x.value; //这里有问题,要用getValue()才对。
}
const T& getValue() const
{
return value;
}
};
int main()
{
MyClass<double> d;
MyClass<int> i;
d.assign(d);
d.assign(i);
return 0;
}
Template classes will be instantiated into specific classes according to usage during compilation.
For example, if the template
MyClass<T>
uses two different instances inmain
, it will be instantiated into two classes:MyClass<double>
andMyClass<int>
. Although these two classes are generated by the same template, They are two different classes, have no friendship relationship, and cannot access each other's private members.Template-related errors are usually difficult to detect during compilation. You can comment out the above
3
statement and it will compile and run normally. However, if you want the3
statement to compile and run, just Private members need to be accessed through thegetValue
member so thatT
andX
can still run when instantiated into different types.In addition, the statement at
1
usesoperator=
for assignment, which raises a potential requirement for the type ofMyClass<T>
templateT
, that is, the typeT
exists and theoperator=
parameter can be passed by the typeX
Converted.Template classes generate different codes based on different specializations at compile time.
x.value
Of course an error will be reported if you use the private attributes of The compiler will not generatesetter
andgetter
, as long as there are no syntax errors in the template class.ps. I changed
main
toMyClass<double>
, and both clang and g++ compiled and passed 233MyClass<int>