注册 登录
编程论坛 C++教室

向量容器的问题

lindayanglong 发布于 2008-09-27 12:24, 743 次点击
下面的程序我想输出a1的值该怎么写呢?
#include<vector>
#include<iostream>
using namespace std;
int i=0;
int j=0;
class Cdemo
{
public:
    Cdemo():str(NULL)
    {
        cout<<"constructor:"<<i++<<endl;
    };

    Cdemo(const Cdemo &cd)
    {
        cout<<"copy constructor:"<<i++<<endl;
        this->str=new char[strlen(cd.str)+1];
        strcpy(str,cd.str);
    };

    ~Cdemo()
    {
        if(str)
        {
            cout<<"destructor:"<<j++<<endl;
            delete [] str;
        }
    };

    char *str;
    };

    int main()
    {
        Cdemo d1;
        d1.str=new char[32];
        strcpy(d1.str,"trend micro");
        vector<Cdemo> *a1=new vector<Cdemo>();
        a1->push_back(d1);
    //    delete a1; vector 对象指针能够自动析构
        cout<<d1.str<<endl;
        cout<<a1<<endl;   //只输出a1的指针
    
        return 0;
    }
2 回复
#2
无缘今生2008-09-27 17:15
vector支持像普通数组一样的随机访问:
例:
vector<int> vc ;
vc.push_back(12);
vc.push_back(4);
vc.push_back(78);

cout << vc[2] << " " << vc[0] << endl; //输出结果是78 12

       vector<Cdemo> *a1=new vector<Cdemo>();
        a1->push_back(d1);
    //    delete a1; vector 对象指针能够自动析构
        cout<<d1.str<<endl;
        cout<<a1<<endl;   //只输出a1的指针
你这里直接输出a1肯定是不行的.它是一个指针,结果应该是一个地址吧?
最后一句可以改成这样:
       cout << a1[0] << endl;  //前提是你的Cdemo类实现了对 << 的重载
#3
blueboy820062008-09-27 20:44
2楼正解啊...
无论是不是指针,关键是对<<重载...
1