본문 바로가기

Language/C++

c++ Operator


Operator


int +

#include <iostream>
#include <vector>
#include <string>
using namespace std;


class addOperator{
private:
	int a = 1;
public:

	addOperator() {};
	~addOperator() {};
	void getnum() {
		cout << this->a << endl;
	}

	addOperator& operator+(const addOperator &ad) {
		/*
		이때는 addOperator에서 &빼고.
		addOperator temp;
		temp.a = this->a + ad.a;
		return temp;
		*/
		this->a += ad.a;
		return *this;
	}

	addOperator operator-(const addOperator &ad) {
		addOperator temp;
		temp.a = this->a - ad.a;
		return temp;
	}
};


int main(int argc, char* argv[]){
	addOperator temp1, temp2;
	(temp1 + temp2).getnum();
	return 0;
}

 

String +

#include <iostream>
#include <string>
using namespace std;

class stringOperator {
private:
	string m_string;
public:
	stringOperator() {};
	stringOperator(const string &_string) {
		this->m_string = _string;
	};

	~stringOperator() {};
	void printString() {
		cout << this->m_string << endl;
	}
	stringOperator& operator+(const stringOperator &s) {
		this->m_string += s.m_string;
		return *this;
	}
};

int main(int argc, char* argv[]) {
	string st1 = "hellow";
	string st2 = " world!";

	stringOperator *string1 = new stringOperator(st1);
	stringOperator *string2 = new stringOperator(st2);

	(*string1 + *string2).printString();

	delete string1;
	delete string2;

	return 0;
}

 

반응형

'Language > C++' 카테고리의 다른 글

c++ malloc new 차이점?  (0) 2019.01.26
c++ thread, mutex, atomic  (0) 2019.01.11
c++ vector capacity  (0) 2019.01.08