0
#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 成员列表?

4

0 回答 0