c ++方法参数给出意外输出

时间:2015-10-28 21:32:12

标签: c++

主类代码:

#include <iostream>
#include "Chair.h"

using namespace std;

int main()
{
cout << "Hello world!" << endl;
Chair c1;
c1.chairType("Olivia",4,32,true);       // not working
Chair c2;
c1.chairType("Stephano",8,8,false);
return 0;
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~

Header class code:

#ifndef CHAIR_H_INCLUDED
#define CHAIR_H_INCLUDED
#include <iostream>


using namespace std;

class Chair
{
private:
    int legCount;
    int height;
    bool cushioned;
    string name;
public:
    void chairType(string newName, int newLegCount, int newHeight, bool cush);


};



#endif // CHAIR_H_INCLUDED

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~

Chair.cpp class:


#include <iostream>
#include "Chair.h"

using namespace std;

void Chair::chairType(string newName, int newLegCount, int newHeight, bool cush)
{
    name=newName;
    legCount=newLegCount;
    newHeight=newHeight;
    cushioned=cush;

    cout<<"I'm a chair, the following are my specs: "<<endl;
    cout<<"Model: "<<name<<endl;
    cout<<"Num of Legs: "<<legCount<<endl;
    cout<<"Height: "<<height<<endl;
    cout<<"Cushioned? : "<<cush<<endl;
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~ 输入到方法中的四个变量的输出是预期的,除了第三个变量(第二个int),打印为2752192,无论我输入什么,以及对象c1和c2。

我是C ++的新手。我一直在练习一些对象类问题,试图熟悉语法。我隐约了解指针有时会导致参考地址打印。但是,这个7位数字似乎不是地址格式。我做了一些搜索,却看不到类似的问题。如果有的话,我会很感激方向。我不想打破网站上发布的条款。提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

class Chair
{
private:
    int legCount;
    int height;
    bool cushioned;
    string name;
public:
    Chair( const string &newName, int newLegCount, int newHeight, bool cush) :
        legCount( newLegCount ),
        height( newHeight ),
        cushioned( cush ),
        name( newName )
    {
    }
    ...
};

int main()
{
    cout << "Hello world!" << endl;
    Chair c1("Olivia",4,32,true);       // works now
    Chair c2("Stephano",8,8,false);
    return 0;
}

应替换为

{{1}}

但更好的是你应该在构造函数中初始化对象,而不是单独的方法:

{{1}}

这样你就不会没有初始化你的类的实例,编译器也会检测到你的错误。

答案 1 :(得分:0)

以下是您的实施 Chair.cpp 中的错误:     newHeight=newHeight;

这是正确的:     height = newHeight;

您得到的长数字是height对象中成员变量Chair的未初始化值。