The code has some problems, I will not fix everything, but I will allow at least it to be compiled:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Nome {
protected:
string nome;
public:
Nome(string _nome) {
nome = _nome;
}
virtual void exibirNome() = 0;
};
class SobreNome : public Nome {
string sobre_nome;
public:
SobreNome(string nome, string _sobre_nome) : Nome(nome) {
sobre_nome = _sobre_nome;
}
void exibirNome() {
cout << nome << " " << sobre_nome;
}
};
int main() {
vector<Nome*> *nome = new vector<Nome*>;
Nome *n = new SobreNome("João", "Alves");
nome->push_back(n);
nome->at(0)->exibirNome();
return 0;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
To use the access by the index operator you have to do this:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Nome {
protected:
string nome;
public:
Nome(string _nome) {
nome = _nome;
}
virtual void exibirNome() = 0;
};
class SobreNome : public Nome {
string sobre_nome;
public:
SobreNome(string nome, string _sobre_nome) : Nome(nome) {
sobre_nome = _sobre_nome;
}
void exibirNome() {
cout << nome << " " << sobre_nome;
}
};
int main() {
vector<Nome*> nome;
Nome *n = new SobreNome("João", "Alves");
nome.push_back(n);
nome[0]->exibirNome();
return 0;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
It’s not time yet but then try to use smart pointers in place of raw pointers. This code is simple and does no damage, but in real code this would leak memory. C++ is not Java, you have to manage the memory.
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class Nome {
protected:
string nome;
public:
Nome(string _nome) {
nome = _nome;
}
virtual void exibirNome() = 0;
};
class SobreNome : public Nome {
string sobre_nome;
public:
SobreNome(string nome, string _sobre_nome) : Nome(nome) {
sobre_nome = _sobre_nome;
}
void exibirNome() {
cout << nome << " " << sobre_nome;
}
};
int main() {
vector<unique_ptr<Nome>> nome;
nome.emplace_back(new SobreNome("João", "Alves"));
nome[0]->exibirNome();
return 0;
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Enter the code more fully for us to see.
– Maniero
I gave an answer assuming a few things, with the full code I could give an even better answer.
– Maniero
@bigown code is just like that
– Vale
I actually had to complete it to get it tested. I made one working, another with the requested adjustment in the reply comment and another using automatic memory management, which is the most correct.
– Maniero