【发布时间】:2016-03-29 20:31:44
【问题描述】:
所以我的程序是我希望用户输入有关板的信息,所以除了我需要用户输入态度值然后添加另一个数字来增加态度的部分之外,一切正常,所以我被困在这。如您所见,我将此函数声明为朋友,但是当我输入需要将其增加到态度值的数字时,它保持不变!我希望我能弄清楚我面临的问题!我会很感激一些帮助
#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* ='\0');
~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]='\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]='\0';
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;
}
【问题讨论】:
-
为什么您认为该功能无法正常工作?
-
你打电话给
incAttitude(hh),然后再也不用hh了。您将需要再次使用 hh 来查看调整的效果 -
@VladfromMoscow 因为例如我输入的态度值 1.6 然后当调用函数 incAttitude 输入一个数字以增加它像 0.1 它打印 1.6(它不增加 :( )
-
@Caroline 查看 Niall 的评论。:)
-
@Niall 我需要在哪里再次使用它!
标签: c++ friend-function