fromctocpp.cpp (2272B)
1 #include <iostream> 2 #include <string> 3 4 class Human 5 { 6 private: 7 std::string name; 8 int age; 9 10 public: 11 Human(std::string name) {this->name = name;} 12 std::string getname() const {return name;} 13 }; 14 15 int modconst(int *, int); 16 void chnames(std::string *, int); 17 void getnames(std::string *, int); 18 int chval(int &, int); 19 int& ref(int *, int); 20 std::string defaultargs(std::string = "No"); 21 22 int main(int argc, char **argv) 23 { 24 // Ερώτημα 1 25 26 // Τρόπος 1 27 const int x = 10; 28 std::cout << "First way" << std::endl; 29 std::cout << "Old const value: " << x << std::endl << "New const value: " << modconst((int *)&x, 15) << std::endl << std::endl; 30 31 // Τρόπος 2 32 int *p = (int *)&x; 33 *p = 35; 34 std::cout << "Second way" << std::endl; 35 std::cout << "Old const value: " << x << std::endl << "New const value: " << *p << std::endl << std::endl; 36 37 // Ερώτημα 2 38 Human *human = new Human("Christos"); 39 std::string *names = new std::string[3]; 40 std::cout << human->getname() << std::endl << std::endl; 41 42 chnames(names, 3); 43 std::cout << std::endl; 44 getnames(names, 3); 45 std::cout << std::endl; 46 47 delete human; 48 delete[] names; 49 50 // Ερώτημα 3 51 int y = 5; 52 std::cout << "Old y value: " << y << std::endl << "New y value: " << chval(y, 10) << std::endl << std::endl; 53 54 int *arr = new int[3]; 55 for (int i = 0; i < 2; i++) arr[i] = i; 56 std::cout << "Old value at index 1: " << arr[1] << std::endl; 57 ref(arr, 1) = 500; 58 std::cout << "New value at index 1: " << arr[1] << std::endl << std::endl; 59 delete[] arr; 60 61 // Ερώτημα 4 62 std::cout << "Function return values: " << std::endl; 63 std::cout << "With default arg: " << defaultargs() << std::endl; 64 std::cout << "Without default arg: " << defaultargs("Yes") << std::endl; 65 66 return 0; 67 } 68 69 void chnames(std::string *names, int numNames) 70 { 71 for (int i = 0; i < numNames; i++) 72 { 73 std::cout << "Name " << i << ": "; 74 std::cin >> names[i]; 75 } 76 } 77 78 void getnames(std::string *names, int numNames) 79 { 80 for (int i = 0; i < numNames; i++) 81 std::cout << "Name " << i << ": " << names[i] << std::endl; 82 } 83 84 int modconst(int *x, int newVal) {return *x = newVal;} 85 int chval(int &y, int newVal) {return y = newVal;} 86 int& ref(int *arr, int index) {return arr[index];} 87 std::string defaultargs(std::string arg) {return arg;}