Ir ao conteúdo
  • Cadastre-se

C++ Sobrecarga de operadores com String em C++.


abreusleo

Posts recomendados

Oi, gente. Preciso fazer uma sobrecarga dos operadores de adição e igualdade com Strings, mas não estou conseguindo. Quando eu realizo o print, recebo "════════²²²²tchau" em vez de "oitchau". Alguem pode me ajudar? Peço perdão por algum erro básico ou algo do gênero, obrigado desde já.
 

#include <iostream>
#include <string.h>

static const int strSize = 1024;

class Strings {
private:
	char* string_;
	size_t length_;

public:
	Strings();
	Strings(const char* s);
	Strings(const Strings& s);
	~Strings() { delete[] string_; };

	const char * GetStr() const { return string_; };

	void SetStr() {
		if (string_ != nullptr) {
			delete[] string_;
		}
		char buffer[strSize];
		std::cin.getline(buffer, strSize);
		length_ = strlen(buffer) + 1;
		string_ = new char[length_];
		strcpy(string_, buffer);
	}
	Strings&operator+(const Strings&);
	Strings&operator=(const Strings&);

	operator char*() { return string_; };

};

Strings::Strings() {
	string_ = nullptr;
	length_ = 0;
}

Strings::Strings(const char* string) : length_{ strlen(string) }, string_{ new char[length_ + 1] } {
	strcpy(string_, string);
}

Strings::Strings(const Strings& string) {
	length_ = string.length_;
	string_ = new char[length_ + 1];
	strcpy(string_, string.string_);
}

Strings& Strings::operator=(const Strings & string) {
	if (this == &string)
		return *this;
	if (length_ != string.length_ || length_ == 0) {
		delete[] string_;
		length_ = string.length_;
		string_ = new char[length_ + 1];
	}
	strcpy(string_, string.string_);
	return *this;
}

Strings& Strings::operator+(const Strings & string) {
	length_ = length_ + string.length_;
	string_ = new char[length_ + 1];
	strcat(string_, string.string_);
	return *this;
}


int main() {
	Strings s("oi");
	Strings s2("tchau");

	Strings s3(s + s2);
	printf("%s", s3);

	delete[] s2;
	delete[] s;

	return 0;
}

 

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...