Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

КМБО 03 21 Поляков А.А. новая ветвь #40

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions animals/animal.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
#include "animal.h"

#include <sstream>
#include <iostream>
using namespace std;

int main() {
return 0;
Cat Scottish(5);
Horse Spirit(1234);
Scottish.set_MiceCaughtCounter(7);
Spirit.setkilometresRun(1500.5);
int res = Scottish.get_MiceCaughtCounter();
float res2 = Spirit.get_kilometresRun();
cout << res << " " << res2 << "\n";
return 0;
}
73 changes: 67 additions & 6 deletions animals/animal.h
Original file line number Diff line number Diff line change
@@ -1,18 +1,79 @@
#pragma once

#include <iostream>
#include <sstream>
using namespace std;


class Animal {
private:
bool CanMoveFreely;
public:
Animal() { CanMoveFreely = 0; }
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не выполнен пункт задания с использованием protected.

Animal(bool YesOrNo) { CanMoveFreely = YesOrNo; }
void setCanMoveFreely(bool YesOrNo) { CanMoveFreely = YesOrNo; }
bool get_CanMoveFreely() const { return CanMoveFreely; }
virtual string about() const { return (stringstream() << "CanMoveFreely =" << CanMoveFreely).str(); }

};

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет перегрузки операции вывода в поток для Animal.


class Mammal :public Animal {
private:
bool FeedsWithMilk;
public:
float weight; // kg
Mammal() { FeedsWithMilk = 0; }
Mammal(bool FeedOrNot) { FeedsWithMilk = FeedOrNot; }
void setFeedsWithMilk(bool FeedOrNot) { FeedsWithMilk = FeedOrNot; }
bool get_FeedsWithMilk() const { return FeedsWithMilk; }
virtual string about() const { return (stringstream() << Animal::about() << ", " << "FeedsWithMilk =" << FeedsWithMilk).str(); }
};

class Mammal : public Animal {
class Cat :public Mammal {
private:
int MiceCaughtCounter;
public:
float pregnancyDuration; // days
Cat(int MiceCaught) { MiceCaughtCounter = MiceCaught; }
void set_MiceCaughtCounter(int MiceCaught) { MiceCaughtCounter = MiceCaught; }
int get_MiceCaughtCounter() const { return MiceCaughtCounter; }
virtual string about() const { return (stringstream() << Animal::about() << ", " << Mammal::about() << ", " << "MiceCaughtCounter =" << MiceCaughtCounter).str(); }
};

class Cat : public Mammal {
class Horse :public Mammal {
private:
float kilometresRun;
public:
float vibrissaLength; // meters
Horse(float distance) { kilometresRun = distance; }
void setkilometresRun(float distance) { kilometresRun = distance; }
float get_kilometresRun() const { return kilometresRun; }
virtual string about() const { return (stringstream() << Animal::about() << ", " << Mammal::about() << ", " << "kilometresRun =" << kilometresRun).str(); }
};


class Birds : public Animal {
private:
int FeathersCounter;
public:
Birds() { FeathersCounter = 0; }
Birds(int Feathers) { FeathersCounter = Feathers; }
void setFeathersCounter(int Feathers) { FeathersCounter = Feathers; }
int get_FeathersCounter() const { return FeathersCounter; }
virtual string about() const { return (stringstream() << Animal::about() << ", " << "FeathersCounter =" << FeathersCounter).str(); }
};
class Pigeon :public Birds {
private:
bool CanBegForBread;
public:
Pigeon(int CheekyOrNot) { CanBegForBread = CheekyOrNot; }
bool get_CanBegForBread() const { return CanBegForBread; }
void setCanBegForBread(int CheekyOrNot) { CanBegForBread = CheekyOrNot; }
virtual string about() const { return (stringstream() << Animal::about() << ", " << Birds::about() << ", " << "CanBegForBread =" << CanBegForBread).str(); }
};
class Caliber :public Birds {
private:
int WingBeatSpeedPerSecond;
public:
Caliber(int BeatCounter) { WingBeatSpeedPerSecond = BeatCounter; }
int get_WingBeatSpeedPerSecond() const { return WingBeatSpeedPerSecond; }
void setWingBeatSpeedPerSecond(int BeatCounter) { WingBeatSpeedPerSecond = BeatCounter; }
virtual string about() const { return (stringstream() << Animal::about() << ", " << Birds::about() << ", " << "WingBeatSpeed =" << WingBeatSpeedPerSecond).str(); }
};
88 changes: 71 additions & 17 deletions electricity/electricity.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,39 @@ using namespace std;

bool Object::isConnectedTo(const Object& other) const
{
// TODO
return false;
for (int i = 0; i < getPoleCount(); ++i) {
auto pole = getPole(i);
if (pole != nullptr && pole->connectedObject == &other)
return true;
}
}

bool Object::connect(const std::string& poleName, Object& other, const std::string& otherPoleName)
{
// TODO
return false;
}
{
if (poleName == otherPoleName && &other == this)
return false;

auto pole = getPole(poleName);
auto otherPole = (Pole*)(other.getPole(otherPoleName));

pole->connectedObject = (Object*)(&other);
pole->connectedObjectPole = otherPoleName;
otherPole->connectedObject = this;
otherPole->connectedObjectPole = poleName;

return true;
}


bool Object::disconnect(const std::string& poleName)
{
// TODO
return false;
{ auto pole = getPole(poleName);
if (pole->connectedObjectPole == "")
return false;
else {
pole->connectedObjectPole = "";
pole->connectedObject = nullptr;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не отключаете другой объект от этого.

return true;
}
}

Switch::Switch(const std::string& name)
Expand All @@ -30,26 +49,61 @@ Switch::Switch(const std::string& name)

const Pole* Switch::getPole(const string& name) const
{
if (name == a1.name)
return &a1;
if (name == a2.name)
return &a2;
if (name == a1.name) return &a1;
if (name == a2.name) return &a2;
return nullptr;
}

const Pole* Switch::getPole(size_t idx) const
{
// TODO
return getPole("A" + to_string(idx + 1));
}
Lamp::Lamp(const string& name)
: Object(name)
, a1("A1")
, a2("A2")
{
}
const Pole* Lamp::getPole(const string& name) const {
if (name == a1.name) return &a1;
if (name == a2.name) return &a2;
return nullptr;
}

const Pole* Lamp::getPole(size_t idx) const {
return getPole("A" + to_string(idx + 1));
}

Generator::Generator(const string& name)
: Object(name)
, a1("A1")
, a2("A2")
, a3("A3")
{
}
const Pole* Generator::getPole(const string& name) const {
if (name == a1.name) return &a1;
if (name == a2.name) return &a2;
if (name == a3.name) return &a3;
return nullptr;
}
const Pole* Generator::getPole(size_t idx) const {
return getPole("A" + to_string(idx + 1));
}

int main()
{
Switch sw, sw2;
sw.connect("A2", sw2, "A1");
cout << "is " << (sw.isConnectedTo(sw2) ? "" : "not ") << "connected" << endl;

// TODO: создать цепь из генератора, выключателя и светильника

Generator generator_test;
Lamp lamp_test;
Switch switch_test;
generator_test.connect("A1", lamp_test, "A1");
lamp_test.connect("A2", switch_test, "A1");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Общее замечание, не касаемо программирования: выключатель ставится до нагрузки (говоря умными словами, коммутирует фазу/плюс, для переменного/постоянного тока, соответственно), чтобы отключать её от потенциала на линии.

cout << "is " << (generator_test.isConnectedTo(lamp_test) ? "" : "not ") << "connected" << endl;
cout << "is " << (lamp_test.isConnectedTo(switch_test) ? "" : "not ") << "connected" << endl;
generator_test.disconnect("A1");
cout << "is " << (generator_test.isConnectedTo(lamp_test) ? "" : "not ") << "connected" << endl;
return 0;
}
27 changes: 23 additions & 4 deletions electricity/electricity.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ class Object {
/// </summary>
/// <param name="idx">Индекс полюса, от <c>0</c> до значения, возвращаемого <see cref="getPoleCount()"/>.</param>
/// <returns>Полюс с указанным индексом, или <c>nullptr</c>, если такой полюс не существует.</returns>
Pole* getPole(size_t idx) { /* TODO */ return nullptr; }
Pole* getPole(size_t idx) {
if (getPole("A" + std::to_string(idx)))
return getPole("A" + std::to_string(idx));
return nullptr;
}

/// <summary>
/// Возвращает полюс по внутреннему индексу устройства.
Expand Down Expand Up @@ -131,7 +135,22 @@ class Switch : public Object {
protected:
virtual const Pole* getPole(size_t idx) const;
};
class Lamp : public Object {
public:
Pole a1, a2;
Lamp(const std::string& name = "");
size_t getPoleCount() const override { return 2; }
const Pole* getPole(const std::string& name) const override;
protected:
const Pole* getPole(size_t idx) const override;
};

// TODO: класс светильника с двумя полюсами

// TODO: класс генератора с тремя полюсами (фаза, нейтраль, земпя).
class Generator : public Object {
public:
Pole a1, a2, a3;
Generator(const std::string& name = "");
size_t getPoleCount() const override { return 3; }
const Pole* getPole(const std::string& name) const override;
protected:
const Pole* getPole(size_t idx) const override;
};
33 changes: 25 additions & 8 deletions memhacks/memhacks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,47 @@
#include "memhacks.h"

using namespace std;
A::A() : a_s("It's a!"), foo(0) {}


B::B() : b_s("It's b!") {
for (auto i = 0; i < sizeof(data) / sizeof(data[0]); i++)
data[i] = i * 2;
}


/// <summary>
/// Выводит на экран адреса и размеры объекта типа <see cref="B"/> и его содержимого.
/// Можно модифицировать для собственных отладочных целей.
/// </summary>
/// <param name="b">Изучаемый объект</param>
void printInternals(const B& b) {
void printInternals(B& b) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если потребовалось отказаться от const для метода, не подразумевающей изменение состояния объекта, то что-то явно сделано не так.

const A* a = &b, * a2 = a + 1;
cout << "Address of b is 0x" << &b << ", address of b.a_s is 0x" << &b.a_s << ", address of b.b_s is 0x" << &b.b_s << endl;
cout << "Size of A is " << sizeof(A) << ", size of B is " << sizeof(B) << endl;
cout << "B string is '" << b.getBString() << "'" << endl;
//cout << "B data: "; b.printData(cout); cout << endl;
cout << "B data printData: "; b.printData(cout); cout << endl;
cout << "B data printData2: "; b.printData2(cout); cout << endl;
}

/// <summary>
/// Извлекает значение <see cref="B::b_s"/> из текущего объекта.
/// Подразумевается, что текущий объект на самом деле представлено классом <see cref="B"/>.
/// </summary>
/// <returns>Значение B::b_s</returns>
std::string A::getBString() const {
// TODO
string A::getBString() const {
return *((const string*)(this + 1));
}

string B::getBString() const {
return b_s;
}

float A::getData(int idx) const {
return ((float*)(this + 2))[idx];
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему (this + 2)?

}

float B::getData(int idx) const {
return data[idx];
}

/// <summary>
Expand All @@ -37,16 +52,18 @@ std::string A::getBString() const {
/// Подразумевается, что текущий объект на самом деле представлено классом <see cref="B"/>.
/// </summary>
void A::printData(std::ostream& os) {
// TODO
os << "A string: " << a_s << ", B string: " << getBString() << ", data: ";
for (int i = 0; i < 7; ++i) os << getData(i) << " ";
}

/// <summary>
/// Извлекает значения <see cref="A::a_s"/>, <see cref="B::b_s"/> и <see cref="B::data"/>
/// из текущего объекта и выводит их в текстовом виде в указанный выходной поток
/// с помощью виртуальных функций, предусмотренных в классе <see cref="A"/>.
/// </summary>
void A::printData2(std::ostream& os) {
// TODO
B b = *((B*)(this));
os << "A string: " << a_s << "', B string: " << b.getBString() << ", data: ";
for (int i = 0; i < 7; ++i) os << b.getData(i) << " ";
}

int main()
Expand Down
20 changes: 10 additions & 10 deletions memhacks/memhacks.h
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
#pragma once

#include <ostream>
#include <string>

using namespace std;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Использовать using namespace в заголовочных файлах нежелательно.

class B; // чтобы можно было объявить printInternals() как friend в классе A

class A {
std::string a_s;
int foo;

friend void printInternals(const B&);
friend void printInternals(B& b);

public:
std::string getBString() const;
A();
virtual string getBString() const;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Идея как раз в том, чтобы продемонстрировать обход штатных (ограничений) средств языка для доступа к полям дочерних классов. В том числе и механизма виртуальных функций.

virtual float getData(int idx) const;
void printData(std::ostream& os);
void printData2(std::ostream& os);
};

class B : public A {
std::string b_s;
float data[7];

friend void printInternals(const B&);
friend void printInternals(B& b);

public:
B();

virtual std::string getBString() const;
virtual float getData(int idx) const;
};

void printInternals(const B& b);
void printInternals(B& b);
Loading