需要C ++ bool编码帮助

时间:2013-04-13 07:59:26

标签: c++ oop

我正在尝试根据下面的要求编写代码(面向对象的编程),但是我的bool保持返回true,而它应该是false。希望你们可以告诉我我的代码出了什么问题。


要求

Member(string = "xxx", bool = false, string = "addr")
Constructor with default values

setMember(string, bool, string): void
Set the values of data members to the respective pass-in values

setPremium(bool): void
Set the value of data member, premium to the pass-in value

getPremium():bool
Returns the value of data member, premium

setMember(string, bool, string): void
Set the values of data members to the respective pass-in values

displayMember():void
Uses cout to display the data members

我的代码

#include <iostream>
#include <string>
using namespace std;

class Member
{
private:
    string name;
    bool premium;
    string address;
public:
    Member(string = "xxx", bool = false, string = "addr");

    void setMember(string, bool, string);
    void setPremium(bool);
    bool getPremium();
    int index;

    void DisplayMember();
};

Member::Member(string name, bool premium, string address)
{
    this-> name = name;
    this-> premium = premium;
    this-> address = address;
}

void Member::setMember(string name, bool premium, string address)
{
    this-> name = name;
    this-> premium = premium;
    this-> address = address;
}

void Member::setPremium(bool)
{
    int i;
    bool premium;
    i = 0;

while (i != 4)
{
    i = i + 1;
}
    if (premium >= 4) 
    {

    index = i;
        premium = true;
    }
    else 
        premium = false;
}

bool Member::getPremium()
{
    return premium;
}

void Member::DisplayMember()
{
    cout<<"Name : "<<name<<endl;
    cout<<"Premium : "<<boolalpha<<premium<<endl;
    cout<<"Address : "<<address<<endl;
}

int main()
{
    Member detail1("Martin ", "2 Tampines Avenue");
    detail1.DisplayMember();

    cin.ignore();
    cin.ignore();
}

2 个答案:

答案 0 :(得分:2)

您的本地bool premium正在隐藏成员变量。要写入后者,您需要使用this->premium或重命名本地变量。除此之外,setPremium代码几乎没有意义 - 例如,您在布尔值上使用整数运算。

这是setPremium应该实现的方式:

void Member::setPremium(bool premium)
{
    this->premium = premium;
}

此外,您正在使用未定义的变量,例如boolalpha。你的代码甚至不应该编译......

答案 1 :(得分:0)

要解决您的问题,只需更改构造函数参数的顺序。

public:
    Member(string = "xxx", string = "addr", bool = false);

Member::Member(string name, string address, bool premium)
{
    this-> name = name;
    this-> premium = premium;
    this-> address = address;
}