#include<iostream>
using namespace std;
#include<conio.h>

class student{
    int roll_no;
    char name[15];
    float per;
public:
    student(int a, char b[15], float c){
        roll_no = a;
        name[15] = b[15];
        per = c;
    }
    ~student(void){
        cout << "Student Details : \n\n"
             << "Roll No : " << roll_no << "\n"
             << "Name : " << name[15] << "\n"
             << "Percentage : " << per << endl;
    }
};

int main(){
    student s(60,"Suraj Jadhav",25.25);
    getch();
    return 0;
}


输出为:
    学生资料:

Roll No : 60
Name :
Percentage : 25.25


名称未显示字符串。
不知道是什么问题,但想解决..请帮助..

最佳答案

当你声明

char name[15];


名称是15个字符的数组。参数b是一个指针(“预期”指向15个字符的数组)。该声明

name[15] = b[15];


仅将“ b”所指向的数组的第16个元素复制到“名称”数组中的第16个元素(计数从零开始),因为数组中有15个元素,因此此处没有定义的行为(使用相同的方式打印名称[15])。

在C语言中,您必须一个接一个地复制每个字符。诸如strcpy之类的功能会为您解决这些问题,如果目标的大小不足以容纳源代码,则可能不安全。
在C ++中,您应尝试避免使用char数组,而应使用std :: string,而take安全地进行复制。
您还应该使用初始化程序列表(用于初始化构造函数中成员的语法)。例如:

#include<iostream>
using namespace std;
#include<conio.h>

class student{
    int roll_no;
    string name;
    float per;
public:
    student(int a, const string &b, float c)
         : roll_no(a), name(b), per(c)
    {
    }
    ~student(){
        cout << "Student Details : \n\n"
             << "Roll No : " << roll_no << "\n"
             << "Name : " << name << "\n"
             << "Percentage : " << per << endl;
    }
};

int main(){
    student s(60,"Suraj Jadhav",25.25);
    getch();
    return 0;
}


注意:#include <conio.h>不是标准的C / C ++,它是特定的MS-DOS标头。尽量避免:)

关于c++ - 字符串未通过构造函数参数传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21464183/

10-11 23:04
查看更多