标题:调试时报错:无法从“std::string”转换为“char [10]”,怎么处理呢?
只看楼主
angle2023
Rank: 1
等 级:新手上路
帖 子:5
专家分:0
注 册:2023-3-13
结帖率:0
已结贴  问题点数:10 回复次数:1 
调试时报错:无法从“std::string”转换为“char [10]”,怎么处理呢?
#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]”,怎么处理呢?
搜索更多相关主题的帖子: Student cout char string std 
2023-03-30 16:56
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:10 
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.
2023-03-31 08:43



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-511740-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.337503 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved