试图从C 中的实例化类中打印出值.结果获取随机值



所以我正在为Microsoft在EDX上的一门课程做一个实验室,他们希望我创建一个名为Person的类构造函数,然后使用构造函数实例化对象并打印出来值。

我遇到的问题是,当我尝试打印出值时,我会得到常见的"随机内存",当您没有给出变量任何数据时获得的值,并且无法弄清楚为什么我会遇到这个问题。请帮助!

这是我的main()函数中的代码,实例化和打印值。

Person *pPerson = new Person("Bob", "Schwimmer", 49, 57, 201);
cout << "His name is: " << pPerson->GetFirstName() << " " << pPerson->GetLastName() << endl;
cout << "He is " << pPerson->GetAge() << endl;
cout << "He weighs (in lbs) " << pPerson->GetWeight() << endl;
cout << "He is " << pPerson->GetHeight() << " feet tall." << endl;

这是我的类构造函数:

class Person
{
    private:
    string firstName;
    string lastName;
    int age;
    int height;
    int weight;
    public:
    Person(string fName, string lName, int age, int height, int weight)
    {
        fName = firstName;
        lName = lastName;
        age = age;
        height = height;
        weight = weight;
    }
    ~Person()
    {
        cout << "Deconstructor has been called" << endl;
    }
    string GetFirstName() { return this->firstName; };
    string GetLastName() { return this->lastName; };
    int GetAge() { return this->age; };
    int GetHeight() { return this->height; };
    int GetWeight() { return this->weight; };
    void SetFirstName(string fName) { fName = this->firstName; };
};

构造函数中的顺序不正确: fname = firstName; 应该是 firstName = fname; 等等。。

最新更新