【问题标题】:Function with classes and vectors variables in c++c++ 中具有类和向量变量的函数
【发布时间】:2020-03-31 21:35:02
【问题描述】:

我有一个名为 Party 的类,其中包含一个名为 player 的私有变量,它是向量类型,sting。

class Party
{
    vector <string> players;

    public: 
    Party (string party_name, string boss)  {}; 
    ~Party() {};        

    vector<string> getNames() { return players; };

    void setNames (const vector<string> &new_players) { players=new_players; }

}

我想编写一个友元函数,它会显示变量 P(也就是具有“名称”变量为私有的类)是否是党的党。

void part_of_party (Party &party, P name)
{   
    bool found=false;

    for (int i=0; ( found==false && i<party.name.size() ); ++i)
    {
        if ( (party.name[i]).compare(name.getName()) == 0)
        {
            found==true;
        };
    }

    if (found==true) { /// }
    else { //// }
}

编译器没有显示任何错误,但屏幕上没有显示任何消息(如预期的那样)。

你有什么想法吗? 谢谢。

【问题讨论】:

标签: c++ function for-loop if-statement vector


【解决方案1】:

我猜是这个问题

found==true;

应该是

found=true;

通常新手会反过来弄错,当他们应该使用==时他们使用=,但是当你应该使用=(分配)时你使用了==(平等)。你的编译器应该已经警告你了。注意编译器警告,它将为您节省大量时间和挫败感。

另外,不是错误,而是

if (party.name[i] == name.getName())

是一种比较明显的写法

if ( (party.name[i]).compare(name.getName()) == 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2012-06-17
    • 1970-01-01
    • 2015-05-25
    • 2018-09-17
    • 2017-03-26
    相关资源
    最近更新 更多