重载的问题 关于#C++#的问题,如何解决?


#include <iostream>
using namespace std;

class Student {
private:
    char* m_name;
    int m_age;
    float m_score;
public:
    //声明构造函数
    Student(char* name, int age, float score);
    //声明普通成员函数
    void show();
};

//定义构造函数
Student::Student(char* name, int age, float score) {
    m_name = name;
    m_age = age;
    m_score = score;
}
//定义普通成员函数
void Student::show() {
    cout << m_name << "的年龄是" << m_age << ",成绩是" << m_score << endl;
}

int main() {
    //创建对象时向构造函数传参
    Student stu("小明", 15, 92.5);
    stu.show();
    //创建对象时向构造函数传参
    Student* pstu = new Student("李华", 16, 96);
    pstu->show();

    return 0;
}

img

我这里也可以运行成功,应该是编译器不同的问题,将参数name,“小明”等换成变量看看,

img

构造函数 声明
改为

Student(const char* name, int age, float score);

构造函数定义改为:

Student::Student(const char* name, int age, float score) {
    m_name = (char*)name;
    m_age = age;
    m_score = score;
}


#include <iostream>
#include <string>

using namespace std;

class Student
{
private:
    string m_name;
    int m_age;
    float m_score;

public:
    //声明构造函数
    Student(const string &name, int age, float score);
    //声明普通成员函数
    void show();
};

//定义构造函数
Student::Student(const string &name, int age, float score)
{
    m_name = name;
    m_age = age;
    m_score = score;
}
//定义普通成员函数
void Student::show()
{
    cout << m_name << "的年龄是" << m_age << ",成绩是" << m_score << endl;
}

int main()
{
    //创建对象时向构造函数传参
    Student stu("小明", 15, 92.5);
    stu.show();
    //创建对象时向构造函数传参
    Student *pstu = new Student("李华", 16, 96);
    pstu->show();
    delete pstu;

    return 0;
}