Enviado em 24/01/2025 - 19:36h
Olá pessoas,Enviado em 27/01/2025 - 02:54h
Quanto de C++17 você usa?#include <memory> class B { public: virtual int f() const = 0; }; class D1: public B { public: int f() const { return 1; } }; class D2: public B { public: int f() const { return 2; } }; int f(const B &b1, const B &b2){ return b1.f()+b2.f(); } int main(){ D1 d1; std::unique_ptr<D2> upd2(new D2); return f(d1, *upd2); }
Enviado em 27/01/2025 - 02:54h
O uso do C++17 pode oferecer várias funcionalidades novas e aprimoramentos em relação ao C++11, como o suporte a estrutura de dados mais poderosas e melhorias na concorrência. No entanto, converter código de C++ para C pode ser desafiador devido às diferenças significativas nas linguagens, especialmente em relação a classes e herança.#include <stdio.h> #include <stdlib.h> typedef struct { int (*f)(void); } B; int D1_f(void) { return 1; } int D2_f(void) { return 2; } int f(B *b1, B *b2) { return b1->f() + b2->f(); } int main() { B d1; B d2; // Ponteiros de função para simular o comportamento das classes d1.f = D1_f; d2.f = D2_f; // A função f agora será chamada com ponteiros para B int result = f(&d1, &d2); printf("%d\n", result); return 0; }
Enviado em 27/01/2025 - 07:49h
SamL, a conversão colocada acima pelo IA do VoL não foi muito fiel ao meu programa original (eu não pedi para imprimir nada), mas até que eu achei interessante: direto ao ponto, produzindo o resultado final (ou algo parecido, já que foi na tela, e não como uma sinalização ao SO), sem se preocupar com a legibilidade. Ficou análogo (em C), do que a gente encontra quando vê o Assembly gerado a partir do código em C++, só que um pouco mais legível.#include <iostream> #include <map> #include <memory> #include <string> #include <cstdlib> #include <ctime> using namespace std; class B { protected: int a; B(int a_=0): a(a_) { } public: virtual int f() const = 0; }; class D1: public B { private: int n; public: // Construtor com todos os argumentos admitindo valores default. D1(int a_=0, int n_=1): B(a_), n(n_) { } int f() const { return a+n; } void d1_out(ostream &os) const { os << "D1(" << a << ", " << n << ")"; } }; class D2: public B { private: int m, n; public: // Overload de construtores com diferentes argumentos. D2(): B(), m(0), n(2) { } D2(int a_): B(a_), m(0), n(2) { } D2(int a_, int m_): B(a_), m(m_), n(m_+2) { } D2(int a_, int m_, int n_): B(a_), m(m_), n(n_) { } int f() const { return a+(m+n)/2; } void d2_out() const { cout << "D2(" << a << ", " << m << ", " << n << ")"; } }; using my_map_t=map<string, unique_ptr<const B>>; void cresce(my_map_t &m, const B *b){ m.emplace("Entrada "+to_string(1+m.size()), move(unique_ptr<const B>(b))); } int range_rand(double r){ return r*(rand()/(RAND_MAX+1.0)); } int main(){ srand(time(nullptr)); my_map_t m; // Popula o mapa. cresce(m, new D1); cresce(m, new D2); for(int i=3; i<13; ++i){ int r=range_rand(5); switch(r){ case 0: cresce(m, new D1(i)); break; case 1: cresce(m, new D1(i, r)); break; case 2: cresce(m, new D2(i)); break; case 3: cresce(m, new D2(i, r)); break; case 4: cresce(m, new D2(i, r, range_rand(i+r))); break; default: cerr << "Valor inesperado de r (" << r << ").\n"; break; } } int soma=0; for(const auto &[nome, dado]: m){ cout << nome << ": "; if(auto pd1=dynamic_cast<const D1 *>(dado.get()); pd1) pd1->d1_out(cout); else if(auto pd2=dynamic_cast<const D2 *>(dado.get()); pd2) pd2->d2_out(); int f=dado->f(); cout << "; f()=" << f << '\n'; soma+=f; } cout << "\nSoma dos f()s=" << soma << ".\n"; }
Enviado em 27/01/2025 - 07:49h
Para converter seu programa em C++ para ANSI C, precisamos considerar que algumas características do C++ não têm equivalência direta no C, como as classes, os construtores e os métodos virtuais. Portanto, faremos algumas adaptações. O programa abaixo reflete uma tradução aproximada para ANSI C, mantendo a lógica do código original:Enviado em 27/01/2025 - 07:52h
Olá! Obrigada pela mensagem.Enviado em 27/01/2025 - 10:50h
------------------------------------------------------| Linux User #621728 |------------------------------------------------------ " Nem sempre é amigo aquele que te tira do buraco !!! ( Saddam Hussein )" ------------------------------------------------------| Linux User #621728 |------------------------------------------------------
Enviado em 27/01/2025 - 10:51h
Olá! Vamos dar continuidade ao seu código C e finalizar a implementação da função `new_D2`. Além disso, explicarei rapidamente a conversão do C++ para C, que é essencial para entender as adaptações.Enviado em 27/01/2025 - 10:54h
------------------------------------------------------| Linux User #621728 |------------------------------------------------------ " Nem sempre é amigo aquele que te tira do buraco !!! ( Saddam Hussein )" ------------------------------------------------------| Linux User #621728 |------------------------------------------------------
Enviado em 27/01/2025 - 10:54h
Olá! Vamos completar a sua mensagem e fazer algumas considerações sobre o seu código.Enviado em 27/01/2025 - 16:12h
@SamL,#include <iostream> #include <map> #include <memory> #include <string> #include <cstdlib> #include <ctime> using namespace std; class B { protected: int a; B(int a_=0): a(a_) { } public: virtual int f() const = 0; }; class D1: public B { private: int n; public: // Construtor com todos os argumentos admitindo valores default. D1(int a_=0, int n_=1): B(a_), n(n_) { } int f() const { return a+n; } void d1_out(ostream &os) const { os << "D1(" << a << ", " << n << ")"; } }; class D2: public B { private: int m, n; public: // Overload de construtores com diferentes argumentos. D2(): B(), m(0), n(2) { } D2(int a_): B(a_), m(0), n(2) { } D2(int a_, int m_): B(a_), m(m_), n(m_+2) { } D2(int a_, int m_, int n_): B(a_), m(m_), n(n_) { } int f() const { return a+(m+n)/2; } void d2_out() const { cout << "D2(" << a << ", " << m << ", " << n << ")"; } }; using my_map_t=map<string, unique_ptr<const B>>; void cresce(my_map_t &m, const B *b){ m.emplace("Entrada "+to_string(1+m.size()), move(unique_ptr<const B>(b))); } int range_rand(double r){ return r*(rand()/(RAND_MAX+1.0)); } int main(){ srand(time(nullptr)); my_map_t m; // Popula o mapa. cresce(m, new D1); cresce(m, new D2); for(int i=3; i<13; ++i){ int r=range_rand(5); switch(r){ case 0: cresce(m, new D1(i)); break; case 1: cresce(m, new D1(i, r)); break; case 2: cresce(m, new D2(i)); break; case 3: cresce(m, new D2(i, r)); break; case 4: cresce(m, new D2(i, r, range_rand(i+r))); break; default: cerr << "Valor inesperado de r (" << r << ").\n"; break; } } int soma=0; for(const auto &[nome, dado]: m){ cout << nome << ": "; if(auto pd1=dynamic_cast<const D1 *>(dado.get()); pd1) pd1->d1_out(cout); else if(auto pd2=dynamic_cast<const D2 *>(dado.get()); pd2) pd2->d2_out(); int f=dado->f(); cout << "; f()=" << f << '\n'; soma+=f; } cout << "\nSoma dos f()s=" << soma << ".\n"; }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define MAX_MAP_SIZE 100 // Base class 'B' (simulated using a struct in C) typedef struct B { int a; int (*f)(const struct B *self); // Virtual function } B; // D1 class (derived from B) typedef struct D1 { B base; // Inheritance: the base class int n; } D1; // D2 class (derived from B) typedef struct D2 { B base; // Inheritance: the base class int m, n; } D2; // Function prototypes int D1_f(const B *self); int D2_f(const B *self); void D1_out(const D1 *self); void D2_out(const D2 *self); // Map entry structure typedef struct MapEntry { char name[50]; B *obj; } MapEntry; // Map (array of entries) MapEntry map[MAX_MAP_SIZE]; int map_size = 0; // Create D1 object D1 *create_D1(int a, int n) { D1 *d = (D1 *)malloc(sizeof(D1)); d->base.a = a; d->base.f = D1_f; d->n = n; return d; } // Create D2 object D2 *create_D2(int a, int m, int n) { D2 *d = (D2 *)malloc(sizeof(D2)); d->base.a = a; d->base.f = D2_f; d->m = m; d->n = n; return d; } // Function implementations int D1_f(const B *self) { const D1 *d = (const D1 *)self; return d->base.a + d->n; } int D2_f(const B *self) { const D2 *d = (const D2 *)self; return d->base.a + (d->m + d->n) / 2; } void D1_out(const D1 *self) { printf("D1(%d, %d)", self->base.a, self->n); } void D2_out(const D2 *self) { printf("D2(%d, %d, %d)", self->base.a, self->m, self->n); } // Add object to map void add_to_map(const char *name, B *obj) { if (map_size < MAX_MAP_SIZE) { strcpy(map[map_size].name, name); map[map_size].obj = obj; map_size++; } } // Generate a random number in the range [0, r] int range_rand(double r) { return (int)(r * (rand() / (RAND_MAX + 1.0))); } int main() { srand(time(NULL)); // Populate the map add_to_map("Entrada 1", (B *)create_D1(0, 1)); add_to_map("Entrada 2", (B *)create_D2(0, 0, 2)); for (int i = 3; i < 13; ++i) { int r = range_rand(5); switch (r) { case 0: add_to_map("Entrada", (B *)create_D1(i, 1)); break; case 1: add_to_map("Entrada", (B *)create_D1(i, r)); break; case 2: add_to_map("Entrada", (B *)create_D2(i, 0, 2)); break; case 3: add_to_map("Entrada", (B *)create_D2(i, r, 2)); break; case 4: add_to_map("Entrada", (B *)create_D2(i, r, range_rand(i + r))); break; default: fprintf(stderr, "Unexpected value of r (%d).\n", r); break; } } // Output the contents of the map int sum = 0; for (int i = 0; i < map_size; i++) { printf("%s: ", map[i].name); if (map[i].obj->f == D1_f) { D1_out((D1 *)map[i].obj); } else if (map[i].obj->f == D2_f) { D2_out((D2 *)map[i].obj); } int f_val = map[i].obj->f(map[i].obj); printf("; f()=%d\n", f_val); sum += f_val; } printf("\nSum of f() values = %d.\n", sum); // Free allocated memory for (int i = 0; i < map_size; i++) { free(map[i].obj); } return 0; }
#include <iostream> #include <map> #include <memory> #include <string> #include <cstdlib> #include <ctime> using namespace std; class B { protected: int a; B(int a_=0): a(a_) { } public: virtual int f() const = 0; }; class D1: public B { private: int n; public: // Construtor com todos os argumentos admitindo valores default. D1(int a_=0, int n_=1): B(a_), n(n_) { } int f() const { return a+n; } void d1_out(ostream &os) const { os << "D1(" << a << ", " << n << ")"; } }; class D2: public B { private: int m, n; public: // Overload de construtores com diferentes argumentos. D2(): B(), m(0), n(2) { } D2(int a_): B(a_), m(0), n(2) { } D2(int a_, int m_): B(a_), m(m_), n(m_+2) { } D2(int a_, int m_, int n_): B(a_), m(m_), n(n_) { } int f() const { return a+(m+n)/2; } void d2_out() const { cout << "D2(" << a << ", " << m << ", " << n << ")"; } }; using my_map_t=map<string, shared_ptr<const B>>; void cresce(my_map_t &m, const B *b){ m.emplace("Entrada "+to_string(1+m.size()), shared_ptr<const B>(b)); } int range_rand(double r){ return r*(rand()/(RAND_MAX+1.0)); } int main(){ srand(time(nullptr)); my_map_t m1; // Popula o mapa. cresce(m1, new D1); cresce(m1, new D2); for(int i=3; i<13; ++i){ int r=range_rand(5); switch(r){ case 0: cresce(m1, new D1(i)); break; case 1: cresce(m1, new D1(i, r)); break; case 2: cresce(m1, new D2(i)); break; case 3: cresce(m1, new D2(i, r)); break; case 4: cresce(m1, new D2(i, r, range_rand(i+r))); break; } } int soma=0; for(const auto &[nome, dado]: m1){ cout << nome << ": "; if(auto pd1=dynamic_cast<const D1 *>(dado.get()); pd1) pd1->d1_out(cout); else if(auto pd2=dynamic_cast<const D2 *>(dado.get()); pd2) pd2->d2_out(); int f=dado->f(); cout << "; f()=" << f << '\n'; soma+=f; } cout << "Soma dos f()s do mapa 1: " << soma << ".\n\n"; my_map_t m2; for(int i=0; i<50; i+=3){ string s("Entrada "+to_string(i)); if(m1.count(s)) m2["Entrada "+to_string(m2.size()+1)]=m1[s]; } soma=0; for(const auto &[nome, dado]: m2){ cout << nome << ": "; if(auto pd1=dynamic_cast<const D1 *>(dado.get()); pd1) pd1->d1_out(cout); else if(auto pd2=dynamic_cast<const D2 *>(dado.get()); pd2) pd2->d2_out(); int f=dado->f(); cout << "; f()=" << f << '\n'; soma+=f; } cout << "Soma dos f()s do mapa 2: " << soma << ".\n\n"; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_MAP_SIZE 100 // Define a base class "B" with a virtual function "f" typedef struct B { int a; int (*f)(const struct B *self); // Virtual function pointer } B; // Define a "D1" class that derives from "B" typedef struct D1 { B base; // Inherit B int n; } D1; // Define a "D2" class that derives from "B" typedef struct D2 { B base; // Inherit B int m, n; } D2; // Define a structure to hold map entries typedef struct MapEntry { char name[50]; B *obj; } MapEntry; // Declare a map with fixed size MapEntry map[MAX_MAP_SIZE]; int map_size = 0; // Function prototypes for constructors, methods, and map operations D1 *create_D1(int a, int n); D2 *create_D2(int a, int m, int n); int D1_f(const B *self); int D2_f(const B *self); void D1_out(const D1 *self); void D2_out(const D2 *self); void add_to_map(const char *name, B *obj); int range_rand(double r); int find_map_index(const char *name); // Create D1 object D1 *create_D1(int a, int n) { D1 *d = (D1 *)malloc(sizeof(D1)); d->base.a = a; d->base.f = D1_f; d->n = n; return d; } // Create D2 object D2 *create_D2(int a, int m, int n) { D2 *d = (D2 *)malloc(sizeof(D2)); d->base.a = a; d->base.f = D2_f; d->m = m; d->n = n; return d; } // D1's virtual function: f() int D1_f(const B *self) { const D1 *d = (const D1 *)self; return d->base.a + d->n; } // D2's virtual function: f() int D2_f(const B *self) { const D2 *d = (const D2 *)self; return d->base.a + (d->m + d->n) / 2; } // Output method for D1 void D1_out(const D1 *self) { printf("D1(%d, %d)", self->base.a, self->n); } // Output method for D2 void D2_out(const D2 *self) { printf("D2(%d, %d, %d)", self->base.a, self->m, self->n); } // Add object to the map void add_to_map(const char *name, B *obj) { if (map_size < MAX_MAP_SIZE) { strcpy(map[map_size].name, name); map[map_size].obj = obj; map_size++; } } // Generate a random number in the range [0, r] int range_rand(double r) { return (int)(r * (rand() / (RAND_MAX + 1.0))); } // Find an entry in the map by name int find_map_index(const char *name) { for (int i = 0; i < map_size; i++) { if (strcmp(map[i].name, name) == 0) { return i; } } return -1; } int main() { srand(time(NULL)); // Create map m1 add_to_map("Entrada 1", (B *)create_D1(0, 1)); add_to_map("Entrada 2", (B *)create_D2(0, 0, 2)); for (int i = 3; i < 13; ++i) { int r = range_rand(5); switch (r) { case 0: add_to_map("Entrada", (B *)create_D1(i, 1)); break; case 1: add_to_map("Entrada", (B *)create_D1(i, r)); break; case 2: add_to_map("Entrada", (B *)create_D2(i, 0, 2)); break; case 3: add_to_map("Entrada", (B *)create_D2(i, r, 2)); break; case 4: add_to_map("Entrada", (B *)create_D2(i, r, range_rand(i + r))); break; default: break; } } // Print the contents of m1 int sum = 0; for (int i = 0; i < map_size; i++) { printf("%s: ", map[i].name); if (map[i].obj->f == D1_f) { D1_out((D1 *)map[i].obj); } else if (map[i].obj->f == D2_f) { D2_out((D2 *)map[i].obj); } int f_val = map[i].obj->f(map[i].obj); printf("; f()=%d\n", f_val); sum += f_val; } printf("Soma dos f()s do mapa 1: %d.\n\n", sum); // Create map m2 MapEntry map2[MAX_MAP_SIZE]; int map2_size = 0; for (int i = 0; i < 50; i += 3) { char s[50]; sprintf(s, "Entrada %d", i); int index = find_map_index(s); if (index != -1) { add_to_map(s, map[index].obj); } } // Print the contents of m2 sum = 0; for (int i = 0; i < map2_size; i++) { printf("%s: ", map2[i].name); if (map2[i].obj->f == D1_f) { D1_out((D1 *)map2[i].obj); } else if (map2[i].obj->f == D2_f) { D2_out((D2 *)map2[i].obj); } int f_val = map2[i].obj->f(map2[i].obj); printf("; f()=%d\n", f_val); sum += f_val; } printf("Soma dos f()s do mapa 2: %d.\n\n", sum); // Free allocated memory for (int i = 0; i < map_size; i++) { free(map[i].obj); } return 0; }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_MAP_SIZE 100 // Define a base class "B" with a virtual function "f" typedef struct B { int a; int (*f)(const struct B *self); // Virtual function pointer } B; // Define a "D1" class that derives from "B" typedef struct D1 { B base; // Inherit B int n; } D1; // Define a "D2" class that derives from "B" typedef struct D2 { B base; // Inherit B int m, n; } D2; // Define a structure to hold map entries typedef struct MapEntry { char name[50]; B *obj; } MapEntry; // Declare a map with fixed size MapEntry map[MAX_MAP_SIZE]; int map_size = 0; // Function prototypes for constructors, methods, and map operations D1 *create_D1(int a, int n); D2 *create_D2(int a, int m, int n); int D1_f(const B *self); int D2_f(const B *self); void D1_out(const D1 *self); void D2_out(const D2 *self); void add_to_map(MapEntry *map, int *map_size, const char *name, B *obj); int range_rand(double r); int find_map_index(MapEntry *map, int map_size, const char *name); // Create D1 object D1 *create_D1(int a, int n) { D1 *d = (D1 *)malloc(sizeof(D1)); d->base.a = a; d->base.f = D1_f; d->n = n; return d; } // Create D2 object D2 *create_D2(int a, int m, int n) { D2 *d = (D2 *)malloc(sizeof(D2)); d->base.a = a; d->base.f = D2_f; d->m = m; d->n = n; return d; } // D1's virtual function: f() int D1_f(const B *self) { const D1 *d = (const D1 *)self; return d->base.a + d->n; } // D2's virtual function: f() int D2_f(const B *self) { const D2 *d = (const D2 *)self; return d->base.a + (d->m + d->n) / 2; } // Output method for D1 void D1_out(const D1 *self) { printf("D1(%d, %d)", self->base.a, self->n); } // Output method for D2 void D2_out(const D2 *self) { printf("D2(%d, %d, %d)", self->base.a, self->m, self->n); } // Add object to the given map void add_to_map(MapEntry *map, int *map_size, const char *name, B *obj) { if (*map_size < MAX_MAP_SIZE) { strcpy(map[*map_size].name, name); map[*map_size].obj = obj; (*map_size)++; } } // Generate a random number in the range [0, r] int range_rand(double r) { return (int)(r * (rand() / (RAND_MAX + 1.0))); } // Find an entry in the map by name int find_map_index(MapEntry *map, int map_size, const char *name) { for (int i = 0; i < map_size; i++) { if (strcmp(map[i].name, name) == 0) { return i; } } return -1; } int main() { srand(time(NULL)); // Create map m1 add_to_map(map, &map_size, "Entrada 1", (B *)create_D1(0, 1)); add_to_map(map, &map_size, "Entrada 2", (B *)create_D2(0, 0, 2)); for (int i = 3; i < 13; ++i) { int r = range_rand(5); switch (r) { case 0: add_to_map(map, &map_size, "Entrada", (B *)create_D1(i, 1)); break; case 1: add_to_map(map, &map_size, "Entrada", (B *)create_D1(i, r)); break; case 2: add_to_map(map, &map_size, "Entrada", (B *)create_D2(i, 0, 2)); break; case 3: add_to_map(map, &map_size, "Entrada", (B *)create_D2(i, r, 2)); break; case 4: add_to_map(map, &map_size, "Entrada", (B *)create_D2(i, r, range_rand(i + r))); break; default: break; } } // Print the contents of m1 int sum = 0; for (int i = 0; i < map_size; i++) { printf("%s: ", map[i].name); if (map[i].obj->f == D1_f) { D1_out((D1 *)map[i].obj); } else if (map[i].obj->f == D2_f) { D2_out((D2 *)map[i].obj); } int f_val = map[i].obj->f(map[i].obj); printf("; f()=%d\n", f_val); sum += f_val; } printf("Soma dos f()s do mapa 1: %d.\n\n", sum); // Create map m2 MapEntry map2[MAX_MAP_SIZE]; int map2_size = 0; for (int i = 0; i < 50; i += 3) { char s[50]; sprintf(s, "Entrada %d", i); int index = find_map_index(map, map_size, s); if (index != -1) { add_to_map(map2, &map2_size, s, map[index].obj); } } // Print the contents of m2 sum = 0; for (int i = 0; i < map2_size; i++) { printf("%s: ", map2[i].name); if (map2[i].obj->f == D1_f) { D1_out((D1 *)map2[i].obj); } else if (map2[i].obj->f == D2_f) { D2_out((D2 *)map2[i].obj); } int f_val = map2[i].obj->f(map2[i].obj); printf("; f()=%d\n", f_val); sum += f_val; } printf("Soma dos f()s do mapa 2: %d.\n\n", sum); // Free allocated memory for (int i = 0; i < map_size; i++) { free(map[i].obj); } return 0; }
Como gerar qualquer emoji ou símbolo unicode a partir do seu teclado
Instalar e Configurar o Slackware Linux em 2025
Como configurar os repositórios do apt no Debian 12 em 2025
Passkeys: A Evolução da Autenticação Digital
Instalação de distro Linux em computadores, netbooks, etc, em rede com o Clonezilla
Configurando o Conky para iniciar corretamente no sistema
3 configurações básicas que podem melhorar muito a sua edição pelo editor nano
Como colorir os logs do terminal com ccze
Instalação Microsoft Edge no Linux Mint 22
Como configurar posicionamento e movimento de janelas no Lubuntu (Openbox) com atalhos de teclado
Site da gontijo simplesmente não abre, ERR_HTTP2_PRO... [RESOLVIDO] (4)