diff --git a/animals/animal.cpp b/animals/animal.cpp index 6745215e..281ee903 100644 --- a/animals/animal.cpp +++ b/animals/animal.cpp @@ -1,7 +1,192 @@ -#include "animal.h" - +#include +#include +#include using namespace std; -int main() { - return 0; -} \ No newline at end of file + + +class Animal { +private: + float the_average_value_of_the_duration_of_life; +public: + void set_the_average_value_of_the_duration_of_life(float new_the_average_value_of_the_duration_of_life) { the_average_value_of_the_duration_of_life = new_the_average_value_of_the_duration_of_life; } + float get_the_average_value_of_the_duration_of_life() const { return the_average_value_of_the_duration_of_life; } + + bool Gender; + virtual string about() const; +protected: + Animal(); + +}; + +string Animal::about() const { + stringstream ss; + ss << "Gender = " << " " << Gender; + return ss.str(); +}; + +class Mammal : public Animal { +private: + int number_of_individuals; +public: + void set_number_of_individuals(int new_number_of_individuals) { number_of_individuals = new_number_of_individuals; } + int get_number_of_individuals() const { return number_of_individuals; } + + string Coat_color; + virtual string about() const; +protected: + Mammal(); +}; + +string Mammal::about() const { + stringstream ss; + ss << Animal::about() << " " << " Coat_color = " << " " << Coat_color; + return ss.str(); +}; + + + +class Quadrupeds : public Mammal { +private: + float percentage_of_quality_of_life; +public: + void set_percentage_of_quality_of_life(float new_percentage_of_quality_of_life) { percentage_of_quality_of_life = new_percentage_of_quality_of_life; } + float get_percentage_of_quality_of_life() const { return percentage_of_quality_of_life; } + + bool limbs; + virtual string about() const; +}; + +string Quadrupeds::about() const { + stringstream ss; + ss << Animal::about() << " " << " limbs = " << " " << limbs; + return ss.str(); +}; + + +class Birds : public Mammal { +private: + int the_average_value_of_the_flight_for_one_season; +public: + void set_the_average_value_of_the_flight_for_one_season(int new_the_average_value_of_the_flight_for_one_season) { the_average_value_of_the_flight_for_one_season = new_the_average_value_of_the_flight_for_one_season; } + int get_the_average_value_of_the_flight_for_one_season() const { return the_average_value_of_the_flight_for_one_season; } + + + bool ability_to_fly; + virtual string about() const; +}; + +string Birds::about() const { + stringstream ss; + ss << Mammal::about() << " " << " ability_to_fly = " << " " << ability_to_fly; + return ss.str(); +}; + +class Cat : public Animal { +private: + int the_number_of_mice_caught_per_unit_of_time; +public: + void set_the_number_of_mice_caught_per_unit_of_time(int new_the_number_of_mice_caught_per_unit_of_time) { the_number_of_mice_caught_per_unit_of_time = new_the_number_of_mice_caught_per_unit_of_time; } + int get_the_number_of_mice_caught_per_unit_of_time() const { return the_number_of_mice_caught_per_unit_of_time; } + + + float vibrissaLength; + virtual string about() const; +}; + +string Cat::about() const { + stringstream ss; + ss << Animal::about() << " " << " vibrissaLength = " << " " << vibrissaLength; + return ss.str(); +}; + +class Manul : public Cat { +private: + int average_weight; +public: + void set_average_weight(int new_average_weight) { average_weight = new_average_weight; } + int get_average_weight() const { return average_weight; } + + + float Average_length_of_wool; + virtual string about() const; +}; + +string Manul::about() const { + stringstream ss; + ss << Cat::about() << " " << " Average_length_of_wool = " << " " << Average_length_of_wool; + return ss.str(); +}; + +class Mainkun : public Cat { +private: + string eye_color; +public: + void set_eye_color(string new_eye_color) { eye_color = new_eye_color; } + string get_eye_color() const { return eye_color; } + + float Number_of_fleas; + virtual string about() const; +}; + +string Mainkun::about() const { + stringstream ss; + ss << Cat::about() << " " << " Number_of_fleas = " << " " << Number_of_fleas; + return ss.str(); +}; + + +Animal::Animal() + : Gender() + , the_average_value_of_the_duration_of_life() +{ + cerr << "" << endl; +} + +Mammal::Mammal() + : number_of_individuals() + , Coat_color() +{ + cerr << "" << endl; +} + +inline ostream& operator <<(ostream& os, const Animal& animal) { + return os << animal.about(); +} + +int main(){ + Mainkun kot_bOris; + Manul kot_Vasily; + Cat Roudi; + Birds ANgry_birds; + Quadrupeds dogs; + + kot_bOris.Gender = true; + kot_bOris.Number_of_fleas = 50000; + kot_bOris.vibrissaLength = 5; + + kot_Vasily.Average_length_of_wool = 3; + kot_Vasily.Gender = true; + kot_Vasily.vibrissaLength = 6; + + Roudi.Gender = true; + Roudi.vibrissaLength = 4; + + ANgry_birds.ability_to_fly = true; + ANgry_birds.Coat_color = "red"; + ANgry_birds.Gender = false; + + dogs.Coat_color = "red"; + dogs.Gender = true; + dogs.limbs = 4; + + cout << "-------------------------------------------------------------" << endl; + cout << "kot_bOris: " << kot_bOris << endl; + cout << "kot_Vasily: " << kot_Vasily << endl; + cout << "Roudi: " << Roudi << endl; + cout << "ANgry_birds: " << ANgry_birds << endl; + cout << "dogs: " << dogs << endl; + cout << "-------------------------------------------------------------"; + + +} diff --git a/classwork/tree.cpp b/classwork/tree.cpp index f9e4dc5d..053252f8 100644 --- a/classwork/tree.cpp +++ b/classwork/tree.cpp @@ -80,47 +80,94 @@ class Tree { } } - void SmallTurnLeft(Node *upper, Node *lower) { - lower -> parent = upper -> parent; - lower -> left = upper; - upper -> parent = lower; - if(lower -> parent != nullptr){ - if(lower ->parent ->left == upper ) {lower ->parent ->left = lower;} - else {lower ->parent -> right = lower;} + void SmallTurnLeft(Node* upper, Node* lower) { + lower->parent = upper->parent; + lower->left = upper; + upper->parent = lower; + if (lower->parent != nullptr) { + if (lower->parent->left == upper) { lower->parent->left = lower; } + else { lower->parent->right = lower; } } - } + }; -public: - class iterator { - Node *node; - iterator(Node *n) : node(n) {} - friend class Tree; - public: - T& operator *() { return node->data; } - iterator& operator ++() { // ++a lvalue +//----------- + class other_iterator { + protected: + Node* node; + other_iterator(Node* n) : node(n) {} + + other_iterator& next() { if (node->right) { node = node->right; while (node->left) node = node->left; - } else { + } + else { while (node->parent && node->parent->right == node) node = node->parent; node = node->parent; } + return *this + } + other_iterator& prev() { + if (node->left) { + node = node->left; + while (node->right) + node = node->right; + } + else { + while (node->parent && node->parent->left == node) + node = node->parent; + node = node->parent; + } + return *this; + } + }; +///----- + +public: + class iterator { + Node *node; + iterator(Node *n) : node(n) {} + friend class Tree; + public: + T& operator *() { return node->data; } + iterator& operator ++() { // ++a lvalue + next(); } iterator operator ++(int) { // a++ rvalue iterator prev = *this; ++(*this); return prev; + } + iterator& operator --() { + auto temp = *this; + --(*this); + return temp; + } + iterator operator --(int) { node->prev(); return *this } + }; + + class reverse_iterator : public other_iterator { + reverse_iterator(Node* n) : other_iterator(n) {} + + friend class Tree; + + public: + T& operator *() { return node->data; } + reverse_iterator& operator--() { + node->next(); return *this; + } + reverse_iterator operator--(int) { + auto temp = *this; + --(*this); + return temp; } - iterator& operator --() { /* TODO */ } - iterator operator --(int) { /* TODO */ } }; - class reverse_iterator { // TODO 1: Написать аналог iterator, работающий в обратном направлении. + // TODO 2: Вынести общий код iterator и reverse_iterator в базовый класс. - }; iterator begin() { if (root == nullptr) @@ -131,8 +178,15 @@ class Tree { return iterator(node); } iterator end() { return iterator(nullptr); } - reverse_iterator rbegin() { /* TODO */ } - reverse_iterator rend() { /* TODO */ } + reverse_iterator rbegin() { + if (root == nullptr) + return rend(); + auto node = root; + while (node->right) + node = node->right; + return reverse_iterator(node); + } + reverse_iterator rend() { return reverse_iterator(nullptr); } Tree() : root(nullptr) {} @@ -274,9 +328,16 @@ int main() { tree.Insert(345, "Bleah"); tree.Insert(893, "Moah"); tree.Insert(043, "CooKoo"); + tree.Insert(935, "Foobarbass"); + tree.Insert(1000, "FooParam"); std::cout << "Printing tree:" << std::endl; tree.Walk(PrintNodeToFile, std::cout); - + cout << "-------------------" << endl; + auto it = tree.rbegin(); + cout << *it << endl; + it--; + cout << *it << endl; + cout << "-------------------" << endl; cout << "Vector:" << endl; std::vector myvector { 121, 443, 565, 323 }; for (size_t i = 0; i != myvector.size(); i++) { diff --git a/electricity/electricity.cpp b/electricity/electricity.cpp index 62da9453..5e0a76c3 100644 --- a/electricity/electricity.cpp +++ b/electricity/electricity.cpp @@ -6,50 +6,112 @@ using namespace std; bool Object::isConnectedTo(const Object& other) const { // TODO + for (size_t idx_1 = 0; idx_1 < this->getPoleCount(); idx_1++) { + + for (size_t idx_2 = 0; idx_2 < other.getPoleCount(); idx_2++) { + + if (this->getPole(idx_1)->connectedObject->name == other.name && this->getPole(idx_1)->connectedObjectPole == other.getPole(idx_2)->name) return true; + } + } return false; } -bool Object::connect(const std::string& poleName, Object& other, const std::string& otherPoleName) +bool Object::disconnect(const std::string& poleName) { // TODO - return false; + if (this->getPole(poleName)->connectedObjectPole != "") { + + this->getPole(poleName)->connectedObjectPole = ""; + + this->getPole(poleName)->connectedObject = nullptr; + + return true; + } + else return false; } -bool Object::disconnect(const std::string& poleName) +bool Object::connect(const std::string& poleName, Object& other, const std::string& otherPoleName) { // TODO + this->getPole(poleName)->connectedObjectPole = otherPoleName; + this->getPole(poleName)->connectedObject = &other; + + other.getPole(otherPoleName)->connectedObject = this; + other.getPole(otherPoleName)->connectedObjectPole = poleName; + return false; } -Switch::Switch(const std::string& name) - : Object(name) - , a1("A1") - , a2("A2") +Switch::Switch(const std::string& name) : Object(name), A1("sw1"), A2("sw2") {} + +Light::Light(const std::string& name_) : Object(name_), A1("l1"), A2("l2") {} + +Power::Power(const std::string& name_) : Object(name_), A1("p1"), A2("p2"), A3("p3") {} + +const Pole* Switch::getPole(const string& name) const { + if (name == A1.name) + return &A1; + if (name == A2.name) + return &A2; + return nullptr; } -const Pole* Switch::getPole(const string& name) const +const Pole* Light::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* Power::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* Switch::getPole(size_t idx) const { - // TODO - return nullptr; + return (getPole("sw" + std::to_string(idx + 1))); } +const Pole* Light::getPole(size_t idx) const +{ + return (getPole("l" + std::to_string(idx + 1))); +} +const Pole* Power::getPole(size_t idx) const +{ + return (getPole("p" + std::to_string(idx + 1))); +} int main() { - Switch sw, sw2; - sw.connect("A2", sw2, "A1"); - cout << "is " << (sw.isConnectedTo(sw2) ? "" : "not ") << "connected" << endl; + cerr << "________________ " << endl; + - // TODO: создать цепь из генератора, выключателя и светильника + Power p; + Light l; + Switch sw; + p.getName("power"); + l.getName("light"); + sw.getName("switch"); + p.connect("p1", l, "l1"); + l.connect("l2", sw, "sw1"); + sw.connect("sw2", p, "p2"); + cout << "Is sw connected l ?" << "\n" << sw.isConnectedTo(l) << endl; + + sw.disconnect("sw1"); + l.disconnect("l2"); + /* + cout << "Is sw connected l ?" << "\n" << sw.isConnectedTo(l) << endl; + */ return 0; } + +// источник -> переключатель -> светильник \ No newline at end of file diff --git a/electricity/electricity.h b/electricity/electricity.h index cb19597b..dc56bc29 100644 --- a/electricity/electricity.h +++ b/electricity/electricity.h @@ -1,5 +1,8 @@ #pragma once -#include +#include +#include + +using namespace std; class Object; @@ -50,7 +53,15 @@ class Object { /// /// Индекс полюса, от 0 до значения, возвращаемого . /// Полюс с указанным индексом, или nullptr, если такой полюс не существует. - Pole* getPole(size_t idx) { /* TODO */ return nullptr; } + Pole* getPole(size_t idx) { + if (idx > getPoleCount()) { + std::string str = "O" + std::to_string(idx); + return getPole(str); + } + else { + return nullptr; + } + }; /// /// Возвращает полюс по внутреннему индексу устройства. @@ -63,7 +74,7 @@ class Object { virtual ~Object() {} const std::string& getName() const { return name; } - void getName(const std::string &newName) { name = newName; } + void getName(const std::string& newName) { name = newName; } /// /// Возвращает полюс по имени. @@ -114,13 +125,12 @@ class Object { /// bool disconnect(const std::string& poleName); }; - /// /// Простой выключатель с двумя полюсами. /// class Switch : public Object { public: - Pole a1, a2; + Pole A1, A2; Switch(const std::string& name = ""); @@ -132,6 +142,39 @@ class Switch : public Object { virtual const Pole* getPole(size_t idx) const; }; -// TODO: класс светильника с двумя полюсами // TODO: класс генератора с тремя полюсами (фаза, нейтраль, земпя). + +class Power : public Object { +public: + Pole A1, A2, A3; + + Power(const std::string& name = ""); + + virtual size_t getPoleCount() const { return 3; } + + virtual const Pole* getPole(const std::string& name) const; + +protected: + virtual const Pole* getPole(size_t idx) const; +}; + +// TODO: класс светильника с двумя полюсами + +class Light : public Object { +public: + Pole A1, A2; + + bool st = false; + + Light(const std::string& name = ""); + + virtual size_t getPoleCount() const { return 2; } + + virtual const Pole* getPole(const std::string& name) const; + +protected: + virtual const Pole* getPole(size_t idx) const; +}; + + diff --git a/memhacks/memhacks.cpp b/memhacks/memhacks.cpp index 514c8689..de0fe321 100644 --- a/memhacks/memhacks.cpp +++ b/memhacks/memhacks.cpp @@ -1,57 +1,19 @@ -#include -#include "memhacks.h" +#include "memhacks.h" using namespace std; -B::B() : b_s("It's b!") { - for (auto i = 0; i < sizeof(data) / sizeof(data[0]); i++) - data[i] = i * 2; -} - -/// -/// Выводит на экран адреса и размеры объекта типа и его содержимого. -/// Можно модифицировать для собственных отладочных целей. -/// -/// Изучаемый объект -void printInternals(const B& b) { - 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; -} - -/// -/// Извлекает значение из текущего объекта. -/// Подразумевается, что текущий объект на самом деле представлено классом . -/// -/// Значение B::b_s -std::string A::getBString() const { - // TODO -} - -/// -/// Извлекает значения , и -/// из текущего объекта и выводит их в текстовом виде в указанный выходной поток -/// с помощью адресной арифметики. -/// Подразумевается, что текущий объект на самом деле представлено классом . -/// -void A::printData(std::ostream& os) { - // TODO -} - -/// -/// Извлекает значения , и -/// из текущего объекта и выводит их в текстовом виде в указанный выходной поток -/// с помощью виртуальных функций, предусмотренных в классе . -/// -void A::printData2(std::ostream& os) { - // TODO -} int main() { + A a; B b; + cerr << " . . . Start executing . . ." << endl; + cerr << "-------------------" << endl; + cout << &a << "\n" << &b << "\n"; printInternals(b); + cout << "MEMHACKS:" << endl; + b.printData(cout); + cout << endl << "Using virtual functions:" << endl; + b.printData2(cout); return 0; -} +} \ No newline at end of file diff --git a/memhacks/memhacks.h b/memhacks/memhacks.h index 51076b55..ed38baac 100644 --- a/memhacks/memhacks.h +++ b/memhacks/memhacks.h @@ -2,29 +2,104 @@ #include #include +#include +#include +using namespace std; -class B; // чтобы можно было объявить printInternals() как friend в классе A +class B; class A { - std::string a_s; + string a_s; int foo; - friend void printInternals(const B&); - + friend void printInternals(B&); public: - std::string getBString() const; - void printData(std::ostream& os); - void printData2(std::ostream& os); + A() : a_s("It's a!"), foo(0) { } + + string getAString() const { return *((const string*)((const float*)(this) + 2)); } + string getBString() const { + return *((const string*)(this + 1)); + } + + + + float getdataFloat(size_t i) { return ((float*)(this + 2) - 4)[i]; } + + virtual string aboutA() const { + stringstream ss; + ss << "String A: " << a_s; + return ss.str(); + } }; + + class B : public A { - std::string b_s; + string b_s; float data[7]; - friend void printInternals(const B&); - + friend void printInternals(B&); public: - B(); + B() : b_s("It's b!") { + for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); i++) + data[i] = (float)i * 2; + } + /// + /// Извлекает значение из текущего объекта. + /// Подразумевается, что текущий объект на самом деле представлено классом . + /// + /// Значение B::b_s + + + virtual string aboutB() { + stringstream ss; + ss << "String B: " << b_s << endl; + ss << "Data : "; + for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); i++) { ss << data[i] << "; "; } + cout << endl; + return ss.str(); + } + + + + + void printData2(ostream& os); + /// + /// Извлекает значения , и + /// из текущего объекта и выводит их в текстовом виде в указанный выходной поток + /// с помощью адресной арифметики. + /// Подразумевается, что текущий объект на самом деле представлено классом . + /// + void printData(ostream& os) { + os << "A string is '" << getAString() << " ', B string is ' " << getBString() << " ' " << endl; + for (size_t i = 0; i < sizeof(data) / sizeof(data[0]); ++i) os << getdataFloat(i) << " "; + } + }; -void printInternals(const B& b); +/// +/// Извлекает значения , и +/// из текущего объекта и выводит их в текстовом виде в указанный выходной поток +/// с помощью виртуальных функций, предусмотренных в классе . +/// +void B::printData2(ostream& os) { + os << aboutA(); + os << aboutB(); +} + + +/// +/// Выводит на экран адреса и размеры объекта типа и его содержимого. +/// Можно модифицировать для собственных отладочных целей. +/// +/// Изучаемый объект +void printInternals(B& b) { + const A* a = &b, * a2 = a; + cerr << "-------------------" << endl; + cerr << "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 << std::endl; + cerr << "Size of A is " << sizeof(A) << ", size of B is " << sizeof(B) << endl; + cerr << "B string is '" << b.getBString() << "'" << endl; + cerr << "B data: "; b.printData(cout); cerr << endl; + cerr << "B data: "; b.printData2(cout); cerr << endl; + cerr << "-------------------" << endl; +} diff --git a/memhacks/newhacks.cpp b/memhacks/newhacks.cpp index ba359c62..385a8225 100644 --- a/memhacks/newhacks.cpp +++ b/memhacks/newhacks.cpp @@ -1,9 +1,106 @@ #include -#include "memhacks.h" +#include "newhacks.h" using namespace std; -int main() +int Foo::next_id; + +Foo::Foo() + : id(++next_id) +{ + cerr << "create object ---> " << id << " at " << this << endl; +} + +Foo::~Foo() +{ + cerr << "delete object ---> " << id << " at " << this << endl; +} + + + + +void* Foo::operator new[](size_t size) +{ + auto p = malloc(size); + cerr << "operator new[](" << size << ") returns " << p << endl; + return p; +} + +void Foo::operator delete[](void* p) { - return 0; + cerr << "operator delete[](" << p << ")" << endl; + free(p); +} + +Foo* create_foo(size_t count) { + return new Foo[count]; +} + +void destruction_foo(Foo* objs) { + delete[] objs; } + + +Bar::Bar() + :Foo() +{ + base = new float(2); +} + +Bar::~Bar() + +{ + delete base; +} + +Buz::Buz() + :Foo() +{ + set = new float(2); +} + +Buz::~Buz() + +{ + delete set; +} + +void* Bar::operator new[](size_t size) +{ + auto p = malloc(size); + cerr << "operator new[](" << size << ") returns " << p << endl; + return p; +} + +void Bar::operator delete[](void* p) +{ + cerr << "operator delete[](" << p << ")" << endl; + free(p); +} + +int main() { + cerr << ". . . start executing . . ." << endl; + //Foo + Foo* obj = new Foo, * obj2 = new Foo; + delete obj; + delete obj2; + obj = new Foo; + obj2 = new Foo; + delete obj2; + delete obj; + + //Bar + Bar* obj11 = new Bar, * obj22 = new Bar; + delete obj11; + delete obj22; + obj11 = new Bar; + obj22 = new Bar; + delete obj22; + delete obj11; + + + + + + return 0; +} \ No newline at end of file diff --git a/memhacks/newhacks.h b/memhacks/newhacks.h index 079a3835..b823c93e 100644 --- a/memhacks/newhacks.h +++ b/memhacks/newhacks.h @@ -1,2 +1,36 @@ #pragma once +#include +class Foo +{ + static int next_id; + int id; + +public: + Foo(); + ~Foo(); + + static void* operator new[](size_t size); + static void operator delete[](void* p); +}; + + +class Buz: public Foo +{ + float *set; +protected: + Buz(); + ~Buz(); +}; + +class Bar : public Foo +{ + float *base; + +public: + Bar(); + ~Bar(); + + static void* operator new[](size_t size); + static void operator delete[](void* p); +}; \ No newline at end of file diff --git a/vectors/array.cpp b/vectors/array.cpp index 555ccadb..5b238140 100644 --- a/vectors/array.cpp +++ b/vectors/array.cpp @@ -1,7 +1,31 @@ +<<<<<<< HEAD #include "array.h" using namespace std; +======= +#include +using namespace std; + +class Vector3d { + float data[3]; +public: + Vector3d() { data[2] = data[1] = data[0] = 0; } + Vector3d(float value) { data[2] = data[1] = data[0] = value; } + float operator[] (int index) const { cerr << "const" << index << endl; return data[index]; } + float& operator[] (int index) { cerr << "non-const" << index << endl; return data[index]; } +}; + +template +class Vector { + float data[Dimensions]; +public: + Vector(float value = 0) { for (size_t i = 0; i < Dimensions; i++) data[i] = value; } + float operator[] (size_t index) const { return data[index]; } + float& operator[] (size_t index) { return data[index]; } +}; + +>>>>>>> electricity homework draft // Написать шаблонные функции: // 1. operator + (реализация внутри класса) // 2. operator * (вектор на скаляр и скаляр на вектор; реализация вне класса) diff --git a/vectors/array.h b/vectors/array.h index 60f50b21..9f1cd114 100644 --- a/vectors/array.h +++ b/vectors/array.h @@ -1,4 +1,5 @@ #pragma once +<<<<<<< HEAD #include @@ -19,3 +20,5 @@ class Vector { float operator[] (size_t index) const { return data[index]; } float& operator[] (size_t index) { return data[index]; } }; +======= +>>>>>>> electricity homework draft diff --git a/vectors/vector.cpp b/vectors/vector.cpp index 9777069c..68471d23 100644 --- a/vectors/vector.cpp +++ b/vectors/vector.cpp @@ -1,25 +1,65 @@ #include -#include "vector.h" +#include using namespace std; +class vector3d { + float data[3]; +public: + vector3d() { data[2] = data[1] = data[0] = 0; } + vector3d(float value) { data[2] = data[1] = data[0] = value; } + vector3d(float a1, float a2, float a3) { data[0] = a1; data[1] = a2; data[2] = a3; } + // lvalue = rvalue + float operator[](int idx) const { return data[idx]; } + float& operator[](int idx) { return data[idx]; } + +}; + + ostream& operator <<(ostream& os, const vector3d& v) { return os << "{ " << v[0] << ", " << v[1] << ", " << v[2] << " }"; } -int main(int argc, char** argv) { - vector3d v1, v2(12), v3(1, 3, 8); - v1[2] = 54; - //vector3d v4 = v1 + v2, v5 = v1 - v2, v6 = v1 * 0.5f; - //cout << "v4: " << v4 << endl << "v5: " << v5 << endl << "v6: " << v6 << endl; - - printf("address of v1: 0x%p, size: %zu bytes\n", &v1, sizeof(v1)); - printf("address of v1.data: 0x%p, size: %zu bytes\n", &v1.data, sizeof(v1.data)); - printf("address of v1.data[-1]: 0x%p, size: %zu bytes\n", &v1.data[-1], sizeof(v1.data[-1])); - printf("address of v1.data[0]: 0x%p, size: %zu bytes\n", &v1.data[0], sizeof(v1.data[0])); - printf("address of v1.data[1]: 0x%p, size: %zu bytes\n", &v1.data[1], sizeof(v1.data[1])); - printf("address of v1.data[2]: 0x%p, size: %zu bytes\n", &v1.data[2], sizeof(v1.data[2])); - printf("address of v1.data[2000]: 0x%p, size: %zu bytes\n", &v1.data[2000], sizeof(v1.data[2000])); - - return 0; +vector3d operator + (const vector3d& v1, const vector3d& v2) { return vector3d(v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]); } +vector3d operator - (const vector3d& v1, const vector3d& v2) { return vector3d(v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]); } +vector3d operator * (const vector3d& v1, const float x) { return vector3d(v1[0] * x, v1[1] * x, v1[2] * x); } +vector3d operator / (const vector3d& v1, const float x) { return vector3d(v1[0] / x, v1[1] / x, v1[2] / x); } +vector3d operator -(const vector3d& v1) { return vector3d(-v1[0], -v1[1], -v1[2]); } +vector3d operator !(const vector3d& v1) { + if (v1[0] == 0 and v1[1] == 0 and v1[2] == 0) { return vector3d(1, 1, 1); } + else return vector3d(0, 0, 0); } + +bool test_vector3d() { + vector3d v1(10, 85, 110); + vector3d v2(20, 65, 90); + + cout << "v1: " << "10, 85, 110" << endl; + cout << "v2: " << "20, 65, 90" << endl; + + bool ERROR = false; + + cout << "v1 + v2 = " << v1 + v2 << endl; + if ((v1 + v2)[0] != v1[0] + v2[0] or (v1 + v2)[1] != v1[1] + v2[1] or (v1 + v2)[2] != v1[2] + v2[2]) { + cerr << "invalid, should be " << "{ " << v1[0] + v2[0] << " " << v1[1] + v2[1] << " " << v1[2] + v2[2] << " }" << endl; + ERROR = true; + } + cout << "v1 - v2 = " << v1 - v2 << endl; + if ((v1 - v2)[0] != v1[0] - v2[0] or (v1 - v2)[1] != v1[1] - v2[1] or (v1 - v2)[2] != v1[2] - v2[2]) { + cerr << "invalid, should be " << "{ " << v1[0] - v2[0] << " " << v1[1] - v2[1] << " " << v1[2] - v2[2] << " }" << endl; + ERROR = true; + } + cout << "v1 * 5 = " << v1 * 5 << endl; + if ((v1 * 5)[0] != v1[0] * 5 or (v1 * 5)[1] != v1[1] * 5 or (v1 * 5)[2] != v1[2] * 5) { + cerr << "invalid, should be " << "{ " << v1[0] * 5 << " " << v1[1] * 5 << " " << v1[2] * 5 << " }" << endl; + ERROR = true; + } + cout << "v1 / 5 = " << v1 / 5 << endl; + if ((v1 / 5)[0] != v1[0] / 5 || (v1 / 5)[1] != v1[1] / 5 || (v1 / 5)[2] != v1[2] / 5) { + cerr << "invalid, should be " << "{ " << v1[0] / 5 << " " << v1[1] / 5 << " " << v1[2] / 5 << " }" << endl; + ERROR = true; + } + return ERROR; +} + +int main(int argc, char** argv) { return test_vector3d(); }