• 15 апреля стартует «Курс «SQL-injection Master» ©» от команды The Codeby

    За 3 месяца вы пройдете путь от начальных навыков работы с SQL-запросами к базам данных до продвинутых техник. Научитесь находить уязвимости связанные с базами данных, и внедрять произвольный SQL-код в уязвимые приложения.

    На последнюю неделю приходится экзамен, где нужно будет показать свои навыки, взломав ряд уязвимых учебных сайтов, и добыть флаги. Успешно сдавшие экзамен получат сертификат.

    Запись на курс до 25 апреля. Получить промодоступ ...

Пример из учебника

  • Автор темы Axe79
  • Дата начала
A

Axe79

учу С++ по "Джесс Либерти - Освой самостоятельно С++ за 21 день"
очень доступно как для чайника))) т.е. дя мну))
и вот конец первой недели и большой листинг ... пообещали что если всё пойму то считай язык почти осилил (шучу, но было б приятно ;) ) и вот набрал, откомпилил, (сижу под Alt Linux компилятор g++) убил все явные ошибки да только что-то не то ... по ходу переменная где-то не ловит значения ...(ниже аут вывел)
вроде как не присваивается... я и так экспериментировал и эдак вся конструкция понятна все метания и ростекания мыслью по коду вроде тоже... хоть дальше иди но .. не хочется оставлять нерешённый вопрос за спиной

Ну что поможете?


C++:
#include <iostream> 
using namespace std;
// intintboolfalsetrue//непонятная фигня
enum CHOICE { DrawRect=1, GetArea, GetPerim, ChangeDimensions, Quit};

class Rectangle // объявляем ректальный классс
{
public:

Rectangle(int width, int heigth); //Инициируем конструктор
~Rectangle();			 //то самое с деструктором

//Методы доступа
int GetHeigth() const {return itsHeigth;}
int GetWidth() const {return itsWidth;}
int GetArea() const {return itsHeigth * itsWidth;}
int GetPerim() const {return 2 * (itsHeigth + itsWidth);}
void SetSize(int newWidth, int newHeigth);

//прочие методы


private:
int itsHeigth;
int itsWidth;
};

//выполнение методов класса
void Rectangle::SetSize(int newWidth, int newHeigth)
{
int itsWidth=newWidth;
int itsHeigth=newHeigth;
}


Rectangle::Rectangle(int Width, int Heigth)
{
int itsHeigth=Heigth;
int itsWidth=Width;
}

Rectangle::~Rectangle() {}

int DoMenu();
void DoDrawRect(Rectangle);
void DoGetArea(Rectangle);
void DoGetPerim(Rectangle);

int main()
{

//Инициализируем объект theRect класа Rectangle с параметрами 30 и 5
Rectangle theRect(30,5);
int choice = DrawRect;
int fQuit = false;

while(!fQuit)
{
choice = DoMenu();
if(choice < DrawRect || choice > Quit)
{
cout << "\n Invalid Choice, please try again.\n\n";
continue;
}
switch (choice)
{
case 	DrawRect:
DoDrawRect(theRect);
break;
case 	GetArea:
DoGetArea(theRect);
break;
case 	GetPerim:
DoGetPerim(theRect);
break;
case 	ChangeDimensions:
int newHeigth, newWidth;
cout << "\n New width ";
cin >> newWidth;
cout << "\n New heigth ";
cin >> newHeigth;
theRect.SetSize(newWidth, newHeigth);
DoDrawRect(theRect);
break;
case 	Quit:
fQuit = true;
cout << "\n Exiting...\n\n";
break;
default	:
cout << "Eror in choice!\n";
fQuit = true;
break;
}				// конец переключателя
}					// конец цикла
return 0;
}					// конец функции main

int DoMenu()
{
int choice;
cout <<"\n\n *** Menu ***\n";
cout <<"(1) Draw Rectangle\n";
cout <<"(2) Area\n";
cout <<"(3) Perimetr\n";
cout <<"(4) Resize\n";
cout <<"(5) Quit\n";

cin >> choice;
return choice;
}

void DoDrawRect(Rectangle theRect)
{
cout << theRect.GetHeigth()<<"\n";
cout << theRect.GetWidth()<<"\n";
int heigth = theRect.GetHeigth();
int width = theRect.GetWidth();

//	for (int i = 0; i<heigth; i++)
//	{
//		 for (int j = 0; j<width; j++)
//	 { cout <<"*";}
//	cout << "\n";
//	}
}


void DoGetArea(Rectangle theRect)
{
cout << "Area: " << theRect.GetArea() << endl;
}

void DoGetPerim(Rectangle theRect)
{
cout << "Perimetr: " << theRect.GetPerim() << endl;
}
это аут
<!--shcode--><pre><code class='dos'>[axe@localhost cppsy]$ g++ 1wee.cpp
[axe@localhost cppsy]$ ./a.out


*** Menu ***
(1) Draw Rectangle
(2) Area
(3) Perimetr
(4) Resize
(5) Quit
1
-1075360568
134516011


*** Menu ***
(1) Draw Rectangle
(2) Area
(3) Perimetr
(4) Resize
(5) Quit
4

New width 5

New heigth 9
-1075360568
134516011


*** Menu ***
(1) Draw Rectangle
(2) Area
(3) Perimetr
(4) Resize
(5) Quit
^C
[axe@localhost cppsy]$[/CODE]
 
V

vital

Оффтоп:
Вы выбрали одну из самых фиговых книжек по C++..
Теперь по делу:
А в чем проблема? Я так и не понял. Код компилится, работает.. ЧТо не так? Научитесь задавать вопросы.
 
V

virtpro

Оффтоп:
Вы выбрали одну из самых фиговых книжек по C++..
Теперь по делу:
А в чем проблема? Я так и не понял. Код компилится, работает.. ЧТо не так? Научитесь задавать вопросы.

какой суровый администратор, а проблема то явна описана. А книжка роли не играет, программированию "научиться нельзя", можно "научиться пользоваться инструментами" реализующими это самое программирование.

А по делу, все оказалось вот в этих строках
void Rectangle::SetSize(int newWidth, int newHeigth)
{
int itsWidth=newWidth;
int itsHeigth=newHeigth;
}
Это из раздела "область видимости", скачай книжку "Язык программирования С++" (автор Бьерн Страуструп), и пользуйся ей как справочником, по ней учиться не рекомендую т.к. уж очень сложно там преподаются знания.

<!--shcode--><pre><code class='С++'>#include <iostream>
using namespace std;

enum CHOICE { DrawRect=1, GetArea, GetPerim, ChangeDimensions, Quit};

class Rectangle // объявляем ректальный классс
{
public:

//Rectangle();
Rectangle(int width, int heigth); //Инициируем конструктор
~Rectangle(); //то самое с деструктором

//Методы доступа
int GetHeigth() const {return itsHeigth;}
int GetWidth() const {return itsWidth;}
int GetArea() const {return itsHeigth * itsWidth;}
int GetPerim() const {return 2 * (itsHeigth + itsWidth);}
void SetSize(int newWidth, int newHeigth);

//прочие методы
private:
int itsHeigth;
int itsWidth;
};

//выполнение методов класса
void Rectangle::SetSize(int newWidth, int newHeigth)
{
itsWidth = newWidth;
itsHeigth = newHeigth;
}
Rectangle::Rectangle(int Width, int Heigth)
{
itsHeigth = Heigth;
itsWidth = Width;
}

Rectangle::~Rectangle() {}

int DoMenu();
void DoDrawRect(const Rectangle &);
void DoGetArea(const Rectangle &);
void DoGetPerim(const Rectangle &);

int main()
{
//Инициализируем объект theRect класа Rectangle с параметрами 30 и 5
Rectangle theRect(30, 5);
int choice = DrawRect;
int fQuit = false;

while(!fQuit)
{
choice = DoMenu();
if(choice < DrawRect || choice > Quit)
{
cout << "\n Invalid Choice, please try again.\n\n";
continue;
}
switch (choice)
{
case DrawRect:
DoDrawRect(theRect);
break;
case GetArea:
DoGetArea(theRect);
break;
case GetPerim:
DoGetPerim(theRect);
break;
case ChangeDimensions:
int newHeigth, newWidth;
cout << "\n New width ";
cin >> newWidth;
cout << "\n New heigth ";
cin >> newHeigth;
theRect.SetSize(newWidth, newHeigth);
DoDrawRect(theRect);
break;
case Quit:
fQuit = true;
cout << "\n Exiting...\n\n";
break;
default :
cout << "Eror in choice!\n";
fQuit = true;
break;
} // конец переключателя
} // конец цикла
return 0;
} // конец функции main

int DoMenu()
{
int choice;
cout <<"\n\n *** Menu ***\n";
cout <<"(1) Draw Rectangle\n";
cout <<"(2) Area\n";
cout <<"(3) Perimetr\n";
cout <<"(4) Resize\n";
cout <<"(5) Quit\n";

cin >> choice;
return choice;
}

void DoDrawRect(const Rectangle &theRect)
{
cout << theRect.GetHeigth()<<"\n";
cout << theRect.GetWidth()<<"\n";
}

void DoGetArea(const Rectangle &theRect)
{
cout << "Area: " << theRect.GetArea() << endl;
}

void DoGetPerim(const Rectangle &theRect)
{
cout << "Perimetr: " << theRect.GetPerim() << endl;
}[/CODE]
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!