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

调试时报错:无法从“std::string”转换为“char [10]”,怎么处理呢?

angle2023 发布于 2023-03-30 16:56, 100 次点击
#include "stdafx.h"
#include<string>
#include <iostream>
using namespace std;
class  Student
{public:
Student(int n,string nam,char s)
{
    num=n;
    name=nam;
    sex=s;
cout<<"Constructor called."<<endl;
};
~Student()
{
    cout<<"Destructor called."<<endl;
}
void display()
{
    cout<<"num:"<<num<<endl;
    cout<<"name:"<<name<<endl;
    cout<<"sex:"<<sex<<endl;
}
private:
    int num;
    char name[10];
    char sex;
};
int main ( )
{
    Student stud1(10010, "Wang_li",'f');
    stud1.display();
    Student stud2(10011, "Zhang_fa",'m');
    stud2.display();
    return 0;
}
调试时报错:无法从“std::string”转换为“char [10]”,怎么处理呢?
1 回复
#2
rjsp2023-03-31 08:43
name=nam; 需要改为 strcpy( name, nam.c_str() );

但最好全部重写
程序代码:
#include <iostream>
#include <string>
#include <string_view>

class  Student
{
public:
    Student( int num, std::string_view name, char sex ) : num_(num), name_(name), sex_(sex)
    {
        std::clog << "Constructor called." << std::endl;
    };
    ~Student()
    {
        std::clog << "Destructor called." << std::endl;
    }

    friend std::ostream& operator<<( std::ostream& os, const Student& stu )
    {
        return os << "{ " << stu.num_ << ", " << stu.name_ << ", " << stu.sex_ << " }";
    }

private:
    int num_;
    std::string name_;
    char sex_;
};

using namespace std;

int main( void )
{
    Student stud1( 10010, "Wang_li", 'f' );
    cout << stud1 << endl;

    Student stud2( 10011, "Zhang_fa", 'm' );
    cout << stud2 << endl;
}


输出
程序代码:
Constructor called.
{ 10010, Wang_li, f }
Constructor called.
{ 10011, Zhang_fa, m }
Destructor called.
Destructor called.
1