String不通过构造函数参数

时间:2014-01-30 18:05:29

标签: c++ string arguments

#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

名称未显示字符串.. 不确定是什么问题但想解决..请帮忙..

4 个答案:

答案 0 :(得分:4)

宣布

char name[15];

name是一个15个字符的数组。参数b是一个指针(“期望”指向15个字符的数组)。声明

name[15] = b[15];

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

在C中你必须一个接一个地复制每个字符。像strcpy这样的函数可以解决这个问题,如果目标不足以容纳源代码,那么它可能是不安全的。 在C ++中,你应该尽量避免使用char数组并使用std :: string代替安全地获取副本。 您还应该使用初始化列表(在构造函数中初始化成员的语法)。例如:

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

答案 1 :(得分:3)

name[15] = b[15];

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

strcpy(name, b);

答案 2 :(得分:2)

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

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

当{b}指向的字符串长度(strncpy()返回且不包括\ 0终结符)等于或大于strlen()的大小时,name存在问题 - 它不会放置\ 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将使您的生活更加简单。

答案 3 :(得分:1)

而不是无效的陈述

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指定名称。