注册 登录
编程论坛 C++教室

一个简单的问题,输出那里为什么不行

菜鸟想成长 发布于 2016-03-22 17:42, 3214 次点击
#include <iostream>
using namespace std;
class Student
{
private:
    int age;
    char *name;
public:
    Student(int,char *);
    Student()
    {
        cout<<"调用系统默认构造函数"<<endl;
    };
    void setname(int,char *);
        int Getage();
        char *Getname();
};
Student::Student(int m,char *n)
    {
        cout<<"调用自定义构造函数"<<endl;
        age=m;
        name=n;
    }
int Student::Getage()
{
    return age;
}
char * Student::Getname()
{
     return name;
}
void Student::setname(int m,char *n)
{
    age=m;
    name=n;
}

int main()
{
    int i;
    char mo,ww;
    Student stu[3]={Student(20,"ww")};
    stu[2].setname(18,"mo");
    for(i=0;i<3;i++)
    {
        cout<<"学生的年龄是:"<<stu[i].Getage()<<"学生的姓名是:"<<stu[i].Getname()<<endl;
    return 0;
}
3 回复
#2
牧羊人942016-03-22 18:09
Student() :name("unknow"), age(0)
    {
        cout << "调用系统默认构造函数" << endl;
    };

你的默认构造函数未初始化!
#3
hjx11202016-03-22 18:27
楼主的代码看着太伤脑细胞,重写了代码

#include <iostream>
#include <string>

class Student{
    private:
        int age;
        std::string name;
    public:
        Student();
        Student(int m, const std::string & n);
        ~Student();
        void Show();
};

Student::Student()
{
    age = 0;
    name = " no name";
}

Student::Student(int m, const std::string & n)
{
    if (m < 0)
    {
        std::cout << "都没出身那来的年龄!" << std::endl;
    }   
    else
    {
        age = m;
        name = n;
    }
}

Student::~Student()
{
   
}

void Student::Show()
{
    std::cout<<"学生的年龄是:"<< age <<"   学生的姓名是:"<< name << std::endl;
}

int main()
{
    Student stu[2]={
        Student(20, "ww"),
        Student(18, "mo")
    };
   
    for(int i = 0;i < 2; i++)
    {
        stu[i].Show();
    }
    return 0;
}
#4
yangfrancis2016-03-23 15:34
回复 楼主 菜鸟想成长
name=n;
把构造函数和setname函数里面的这一句改成strcpy()函数试试
1