朋友功能出现问题

trouble with friend function

本文关键字:问题 功能 朋友      更新时间:2023-10-16

所以我的程序是,我希望用户输入关于一块板的信息,这样除了我需要用户输入态度值的部分之外,所有的东西都能工作,然后再加一个数字来增加态度,所以我只能这样做。正如你所看到的,我作为朋友声明了这个函数,但当我输入需要将其增加到态度值的数字时,它保持不变!我希望我把我面临的问题说清楚了!我很感激的帮助

#ifndef BOARD_H
#define BOARD_H
class Board {

friend void incAttitude(Board &);

public:
friend void incAttitude(Board &);
static int boardcount;
Board(int=5,int=3,double=1.5,char* ='');
~Board();
Board &setBoard(int,int,double,char*);
char getLocation();
Board &print();
double surface();

private:
const int length;
int width;
double attitude;
char location[30];

};
#endif
#include<iostream>
#include<cstring>
#include<string>
#include<assert.h>
using namespace std;
#include "Board.h"
int Board::boardcount=0;
Board::Board(int l,int w,double a,char* lo)
    : length(l)
{
width=w;
attitude=a;
location[0]='';
boardcount++;
}

Board::~Board(){
boardcount--;
}
Board &Board::setBoard(int l,int w,double a,char* lo)
{   
    width=(w>=2 && w<=5)?w:3;
    attitude=(a>=1.5 && a<=2.8)?a:1.5;
    strncpy_s(location,lo,29);
    location[29]='';
    return *this;
}
char Board::getLocation(){

    return *location;
}
double Board::surface(){
return length*width;
}
void incAttitude(Board &h)
{
 double incAttitude;
cout<<"enter to increase attitude "<<endl;
cin>>incAttitude;
h.attitude+=incAttitude;
cout<<"the attitude of the board after the increase : "<<h.attitude<<endl;
}
Board &Board::print(){
    cout<<"the length of the boarad : "<<length<<endl;
    cout<<"the width of the board : "<<width<<endl;
    cout<<"the height of the board : "<<attitude<<endl;
    cout<<"the location of the board : "<<location<<endl;
    cout<<"the surface of the board : "<<surface()<<endl;
    return *this;
}
int main(){
    Board hh;
    Board *boardptr;
int count,len,wid;
double att;
char locat[30];

cout<<"how many boards do you need to create ? "<<endl;
cin>>count;
boardptr = new Board[count];
assert(boardptr!=0);

for (int i=0; i<count; i++){
 cout << "Enter the length: ";
 cin >>len;
 cout << "Enter the width: ";
 cin >> wid;
 cout << "Enter the attitude: ";
 cin >> att;
  incAttitude(hh);
 cout<<"Enter the location: ";
 cin >>locat;
 boardptr[i].setBoard(len,wid,att,locat);
 cout<<"------------------------------------------"<<endl;
  if (strcmp("NewYork",locat) == 0) 
  {
     boardptr[i].setBoard(len,wid,att,locat).print();
  }
}

delete [] boardptr;
system("pause");
return 0;
}

您有一个Boards的数组,称为boardptr。但什么是hh?一块木板。它做什么?没有什么但您正在incAttitude(hh);中使用它!它确实增加了高度,但不是在boardptr[i](你正在使用的)板上,而是在hh上。

其次,您从不设置att,这意味着高度始终为1.5(这是默认值)。所以incAttitude将数字加到1.5上。例如,您可以将att传递给incAttitude


那么,如果你的比较条件,为什么要重新设置棋盘呢?它重置用户选择的每个值。您不需要,因为您已经提前几行呼叫了setBoard。使用setBoard设置的数据保存在该数组中,因此不需要用完全相同的数据覆盖数据。只需使用boardptr[i].print()即可。
char数组、strcmp、原始指针和固定大小数组都来自C,您应该考虑其他选择:

  • 字符数组->std::string
  • strcmp->if (str == "foo")
  • 原始指针->智能指针(或者在您的情况下(因为它们被用作数组)std::arraystd::vector-std::vector用于动态大小的数组)
  • 固定大小阵列->std::array