我创建了一个名字很好的类,它有一个打印状态的函数;在我构建它们之后写作“well w1,w2,w3 .....,w10;”它们中的8个或9个打印相同的状态,但是其中1个或2个打印另一个状态(我定义了总共4个状态,并且最初它具有默认状态,其中8-9个对象正确打印)。
我使用CodeBlocks并且通过“#include”well.h“”添加了井类。 所以总之;我定义一个类并通过编写它们的名称来创建对象,其中一些行为与其他行为不同。
enter code here
#include <iostream>
#include "myQueue.h"
#include "well.cpp"
using namespace std;
int main(){
Well w1,w2,w3,w4,w5,w6,w7,w8,w9,w10;
w1.checkState();
w1.printState();
w2.checkState();
w2.printState();
w3.checkState();
w3.printState();
w4.checkState();
w4.printState();
w5.checkState();
w5.printState();
w6.checkState();
w6.printState();
w7.checkState();
w7.printState();
w8.checkState();
w8.printState();
w9.checkState();
w9.printState();
w10.checkState();
w10.printState();
return 0;
}
class implementation
include "well.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
Well::Well()
{
int state = 4;
int day = 1;
float storage = 2.0;
int offday = 0;
int useCount = 0;
}
int Well::checkState()
{
if (storage==0)
{if (useCount==2) state = 3; // dry and broken
else state = 1;} //dry
else if (useCount==2) state = 2; //broken
else state = 4; // available
}
void Well::printState()
{
if (state==1) cout << "d" << endl;
else if (state==2) cout << "b" << endl;
else if (state==3) cout << "db" << endl;
else if(state==4) cout << "avai"<< endl;
}
void Well::GFG()
{
checkState();
if (state !=2 ) {storage= min(5.0,storage + 0.5 );
checkState(); };
}
void Well::SP()
{
if (state == 4 )
{
storage = max(0.0, storage-1.0);
useCount++;
checkState();
}
}
float Well::getStorage() const
{
return storage;
}
void Well::newDay()
{
++day;
GFG();
--offday;
useCount=0;
checkState();
}
on screen
avai
avai
d
avai
avai
avai
avai
d
avai
avai
答案 0 :(得分:1)
此代码:
Well::Well()
{
int state = 4;
int day = 1;
float storage = 2.0;
int offday = 0;
int useCount = 0;
}
不初始化类的成员。它初始化构造函数中的局部变量。提高编译器的警告级别以获取有关此类未使用变量的警告。
这是一个初始化成员的变体:
Well::Well()
: state( 4 )
, day( 1 )
, storage( 2.0 )
, offday( 0 )
, useCount( 0 )
{}
检查您最喜欢的C ++教科书以获取初始化语法。