search

Home  >  Q&A  >  body text

C++参数初始化表的问题

1.下面代码有问题吗?

#include <iostream>
#include <string.h>
using namespace std;
class A
{
public:
    A(char * ps)
        :name(ps), len(strlen(name.c_str())) {}
    void dis()
    {
        cout << len << endl;
    }
private:
    int len;
    string name;
};
int main()
{
    A a("china");
    a.dis();
    return 0;
}

问题在哪?

大家讲道理大家讲道理2773 days ago378

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 14:42:53

    Write the data member string name; in front of int len;. Because data members are initialized in the order of declaration. If the name has not been initialized, how can you use the len of the name.

    reply
    0
  • PHPz

    PHPz2017-04-17 14:42:53

    Char* type cannot be passed to string type

    reply
    0
  • Cancelreply