두 객체의 값 서로바꾸는것 도와주세요ㅠㅠ

익명 사용자의 이미지

main문 안의 cout부분을 a.n, b.n으로 고치면 출력되는건 알고있지만
main문을 고치지 않고 a, b의 값을 바꿔서 출력할수 있는 방법을 알고싶습니다ㅠㅠ

#include <iostream>
 
using namespace std;
 
class X {
public:
	int n;
};
 
void change(X &x, X &y) {
	X p;
	p.n = x.n;
	x.n = y.n;
	y.n = p.n;
}
 
int main() {
	X a{ 1 };
	X b{ 2 };
 
	change(a, b);
 
	cout << a << ", " << b << endl;
}

raymundo의 이미지

main 을 안 고치려면 << 연산자를 오버로드하셔야...?

class X {
public:
   int n;
   friend ostream& operator<<(ostream& os, const X& x);
};
 
ostream& operator<<(ostream& os, const X& x) {
    os << x.n;
    return os;
}

좋은 하루 되세요!

익명 사용자의 이미지

정말 감사합니다!

익명 사용자의 이미지

결과적으로 볼 때 질문 내용은 "두 객체의 값 서로바꾸는것"과는 그닥 상관이 없군요.
심심해서 조금 손 댔습니다.

#include <iostream>
#include <utility> // for swap (since C++11)
using namespace std;
 
// Forward declarations
class X;
ostream &operator<<(ostream &, const X&);
 
class X {
public:
	int n;
	ostream &streamOut(ostream &out) const{return (out << n);}
};
 
ostream &operator<<(ostream &out, const X& x){return x.streamOut(out);}
 
void change(X &x, X &y) {
	swap(x, y);
}
 
int main() {
	X a{ 1 };
	X b{ 2 };
 
	change(a, b);
 
	cout << a << ", " << b << endl;
}
익명 사용자의 이미지

답변 감사합니다ㅠㅠ!

swish95의 이미지

다들 소통의 천재 인듯^^

저는 질문 자체가 이해가 안되고 있는데 거기에 답글을 두분이나 다셨네요
코드 자체의 의미는 이해합니다만 무슨 의미가 있는지 이해가 안됩니다.
물론 제가 이해할 필요 없겟지만요 ^^

------------------------------------------------------------
ProgrammingHolic

익명 사용자의 이미지

소통이라고 할 것까지는 없죠.
그냥 마음 가는 대로 읽고 끄적일 뿐입니다. 질문자한테 정말로 도움이 될지 안될지는 알 바 아니고...

그보다, C++에서 저런 꼴의 클래스에서는 따로 생성자를 만들지 않고 aggregate initialization을 할 수 있다는 거 흥미롭지 않습니까?

나름 C++를 꽤 오래 썼다고 생각했는데 저런 기능을 안 지는 얼마 되지 않아서, 몇 년 전까지만 해도 trivial한 구조체에 trivial한 생성자를 일일히 짜 넣느라 삽질을 하는 경우가 많았죠.

대체로 이런 종류의 사소한 편의 기능을 설명하는 데 일일이 지면을 할애하지 않는 C++ 교본들 탓을 할 수도 있겠지만, 사실 본질적인 책임은 C++언어 (사실은 C언어...)를 꼼꼼하게 공부하지 않은 제 탓입니다. 흑흑...

swish95의 이미지

뭐 그렇죠...

그냥 답글 달고 싶으면 다는건 저도 그렇습니다.

C++ 의 저런 기능들이 강력하긴 하죠 ^^
그래서 난해하게 짤려면 얼마든지 가능한면도 있구요 .

뭐 다른 언어들도 그덕에 유사한 기법들이 존재하는 이유라고나 할까요 ㅋ

------------------------------------------------------------
ProgrammingHolic

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.