繁体   English   中英

字符串未通过构造函数参数传递

[英]String is not passing through constructor argument

#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标头。 尽量避免:)

name[15] = b[15];

不会复制字符串。 它将仅从b复制一个字符到name ,特别是索引15的那个字符。(实际上,这实际上是未定义的行为,因为每个数组仅具有索引0..14。)尝试以下操作:

strcpy(name, b);

如果您不理解原始指针,则不应使用它们,而应使用std :: string。 无论如何,您的构造函数可以像这样固定:

student(int a, const char *b, float c){
    roll_no = a;
    strncpy( name, b, sizeof( name ) );
    per = c;
}

当b指向的字符串长度等于或大于name大小时,字符串长度( strlen()返回的内容,但不包括\\ 0终止符)存在strncpy()问题-不会将\\ 0终止符放入目标字符串中。 因此,这样可以使代码更安全:

student(int a, const char *b, float c){
    roll_no = a;
    name[ sizeof( name ) - 1 ] = 0;
    strncpy( name, b, sizeof( name ) - 1 );
    per = c;
}

同样,使用原始指针非常复杂,您需要深入了解编写安全代码的过程。 在C ++中使用std :: string将使您的生活变得更加简单。

代替无效的陈述

name[15] = b[15];

您应该使用标头中声明的C标准函数strcpy

std::strcpy( name, b );

同样,构造函数的正确声明将如下所示

student(int a, const char b[15], float c);

要么

student(int a, const char b[], float c);

要么

student(int a, const char *b, float c);

这三个声明声明了相同的功能。

为了使构造函数安全,我将其定义为

student(int a, const char b[], float c){
        roll_no = a;
        std::strncpy( name, b, 15 );
        name[14] = '\0';
        per = c;
}

同样,使用枚举器或静态常量为魔术数字15分配名称也是个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM