當我試圖輸入x pt.1的任何座標時,我的程序只是簡單地掛起。C++,當我使用這種數組來存儲數據時,爲什麼我的程序掛起?
任何人都可以幫助我嗎?
// shape.h
#include <string>
#ifndef SHAPE_H
#define SHAPE_H 1
using namespace std;
class Shape
{
protected:
int x, y;
string name;
public:
// a simple inline constructor
Shape(int new_x, int new_y, string new_name): x(new_x), y(new_y), name(new_name)
{
return;
};
virtual ~Shape()
{
return;
};
// inline getter/setter functions
string getName() { return name; };
void setName(string new_name)
{
name = new_name;
}
int getX() { return x; };
void setX(int set_x)
{
x = set_x;
}
int getY() { return y; };
void setY(int set_y)
{
y = set_y;
}
void toString();
};
#endif
形狀標題。這個方案是關於繼承太..
// square.h
#ifndef SQUARE_H
#define SQUARE_H 1
#include <string>
#include "Shape.h"
using namespace std;
class Square : public Shape
{
protected:
int size;
public:
// a c'tor that calls the parent class's c'tor
Square(int new_x, int new_y, string new_name): Shape(new_x, new_y, new_name)
{
return;
};
void setXY();
Square *arraySquare[1];
};
void Square::setXY()
{
int count = 0;
for(int i=0; i<4; i++)
{
cout<<"Please enter x-ordinate of pt. "<<i+1<<" : ";
cin>>x;
arraySquare[count]->setX(x);
cout<<"Please enter y-ordinate of pt. "<<i+1<<" : ";
cin>>y;
arraySquare[count]->setY(y);
count++;
}
}
#endif
方頭..形狀的一個子類..
#include <iostream>
#include <string>
#include "Shape.h"
#include "Square.h"
using namespace std;
class Main
{
public:
void mainMenu();
char menuChoice;
void stringToUpper(string &s);
};
void stringToUpper(string &s)
{
for(unsigned int l = 0; l < s.length(); l++)
{
s[l] = toupper(s[l]);
}
}
void Main::mainMenu()
{
cout<<"Welcome to Main program!"<<endl<<endl;
cout<<"1) Input data"<<endl;
cout<<"2) 2"<<endl;
cout<<"3) 3"<<endl;
cout<<"4) 4"<<endl;
cout<<"Q) Enter 'Q' to quit"<<endl<<endl;
}
int main()
{
char menuChoice;
bool quit=false;
Main main;
Square *square;
string shape, special;
while (!quit)
{
main.mainMenu();
cout<<"Please enter your choice : ";
cin>>menuChoice;
menuChoice = toupper(menuChoice);
switch(menuChoice)
{
case '1':
cout<<endl<<"[ Input data ]"<<endl;
cout<<"Please enter name of shape : "<<endl;
cin>>shape;
stringToUpper(shape);
if(shape=="SQUARE")
{
square->setXY();
}
break;
case '2':
cout<<"Print"<<endl<<endl;
break;
case '3':
cout<<"You choosen 3"<<endl<<endl;
break;
case '4':
cout<<"You choosen 4"<<endl<<endl;
break;
case 'Q':
cout<<"You have chosen to quit!"<<endl<<endl;
quit=true;
exit(0);
default:
cout<<"Invalid entry!"<<endl<<endl;
break;
}
}
}
這是該方案的面..
它只是掛起每當我運行它並輸入第一個座標x。任何人都可以幫忙
變量'square'是一個未初始化的'Square *'並被解除引用,導致未定義的行爲。 – hmjd
另外你還要經過'arraySquare'這個未定義的行爲。 – Dan
嘗試使用調試器來查看會發生什麼。可能不是因爲數組,而是該cin處於錯誤狀態。 – Axel