| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 514 人关注过本帖
标题:调试时报错:无法从“std::string”转换为“char [10]”,怎么处理呢?
只看楼主 加入收藏
angle2023
Rank: 1
等 级:新手上路
帖 子:6
专家分: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
等 级:版主
威 望:528
帖 子:9024
专家分:54030
注 册: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
快速回复:调试时报错:无法从“std::string”转换为“char [10]”,怎么处理呢? ...
数据加载中...
 
   



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

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