c++中模板类的问题
PHP中文网
PHP中文网 2017-04-17 13:26:52
0
2
377

如下面的这段代码所示,模板类里面有一个模板成员函数,其中有问题的地方我已经标注了,就是注释的那一行。请问为什么要用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;
}

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
伊谢尔伦

Template classes will be instantiated into specific classes according to usage during compilation.

For example, if the template MyClass<T> uses two different instances in main, it will be instantiated into two classes: MyClass<double> and MyClass<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<typename T>
class MyClass
{
private:
    T value;
public:
    /* ... */
    template <typename X>
    void assign(const MyClass<X>& x)
    {
        value = x.value;  // 1. 当类型 X 与 T 相同时,则为同一个类,可以访问自己的私有成员
                          //    当类型 X 与 T 不同时,则不是同一个类,不能访问对方的私有成员
    }
    const T& getValue() const
    {
        return value;
    }
};

int main()
{
    MyClass<double> d;
    MyClass<int> i;
    d.assign(d);  // 2. X 与 T 相同,正常编译运行
    d.assign(i);  // 3. X 与 T 不同,编译报错
    return 0;
}

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 the 3 statement to compile and run, just Private members need to be accessed through the getValue member so that T and X can still run when instantiated into different types.


In addition, the statement at 1 uses operator= for assignment, which raises a potential requirement for the type of MyClass<T> template T, that is, the type T exists and the operator= parameter can be passed by the type XConverted.

迷茫

Template classes generate different codes based on different specializations at compile time.
x.valueOf course an error will be reported if you use the private attributes of The compiler will not generate setter and getter, as long as there are no syntax errors in the template class.
ps. I changed main to MyClass<double>, and both clang and g++ compiled and passed 233MyClass<int>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template