如何使用初始化列表初始化类的const char数组成员?

时间:2012-04-24 13:15:51

标签: c++

#include<iostream>

using std::cout;
using std::endl;

/*
This example aims to test whether the default copy constructor and default assignment operator works for classes that has array member and whether initialzation list works for array member.

Test result: copy constructor and default assignment operator works for classes that has array member
                         initialization list doesn't work for array member.
*/

class A{
    private:
        const char list[10];
    public:
        A(const char *l="Nothing");
        void show()const;

};

A::A(const char*l):list(l){           //the compiler fails to initialize "list"
}

void A::show()const{
    for(int i=0;i<10;i++){

        cout<<list[i]<<'\t';
        if(i%5==4)
            cout<<endl;
        }
    cout<<endl;
}

int main(){
    char name[10]="hello";
    A a(name);
    A b;
    cout<<"Before assignment, b="<<endl;
    b.show();
    b=a;
    cout<<"After assignment, b="<<endl;
    b.show();
    A c(a);
    cout<<"After initialization, c="<<endl;
    c.show();

}

程序无法编译并抛出错误消息,称“将'const char *'赋值给'const char [10]”时出现“不兼容的类型”。如何初始化const成员列表?

0 个答案:

没有答案