模板对象和基元

时间:2014-12-14 12:44:20

标签: c++ visual-c++

我有以下类模板,它将接受基元和对象。但是像这样我只能打印基元。如何使用基元和对象使其运行?感谢

template<class T>

    class A
    {

        private:
            vector <T> l;
        public:

            void print() const
            {
                for (int i=0;i<.size();i++)
                {
                    cout<<l[i]<<endl; //error here
                }

            } 
    };

2 个答案:

答案 0 :(得分:0)

您可以打印基元的原因是<iostream>operator<<提供了重载。

要让模板以相同的方式打印您的类,您需要定义自己的运算符实现:

// This implementation puts operator << outside your class.
// Mark it "friend" in MyClass if it needs access to private members of MyClass.
ostream& operator<<(ostream& ostr, const MyClass& myClass) {
    // Do the printing based on the members of your class
    ostr << myClass.member1 << ":" << myClass.member2;
    return ostr;
}

编译器将在模板扩展期间检测此运算符,并在执行此操作时将其用于打印:

cout<<l[i]<<endl;

您也可以将operator<<放入班级:

ostream &operator<<(ostream &os) {
    ostr << member1 << ":" << member2;
}

答案 1 :(得分:0)

我假设在这里,您想要打印一个对象而不是属于基本数据类型的变量。

对于这种情况,您可以在C ++中查看运算符重载(更具体地说是重载插入运算符)。

有关重载对象的插入运算符的详细信息,可以访问此URL

http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

下面给出了一个关于如何实现它的例子

ostream& operator<<(ostream& os, const Datatype& dt) 
{
os << dt.a <<" " << dt.b;
return os;
}

ostream& operator<<(ostream& os, const Datatype& dt) { os << dt.a <<" " << dt.b; return os; }

此处数据类型是类的名称,而a和b是a和b的两个私有成员,当您尝试打印对象时将打印这些成员。

但是,要使用此技术重载,请不要忘记将此函数作为类的友元函数(如下所示),因为函数需要访问类的私有成员。

friend ostream& operator<<(ostream& os, const Datatype& dt);

相关问题