반응형
Java의 toString과 동등한 C ++?
스트림에 쓰여지는 내용, 즉 cout
사용자 정의 클래스의 객체 를 제어하고 싶습니다 . C ++에서 가능합니까? Java에서는 toString()
비슷한 목적으로 메소드를 대체 할 수 있습니다 .
C ++에서 당신은 오버로드 할 수 있습니다 operator<<
에 대한 ostream
귀하의 사용자 정의 클래스 :
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
이런 식으로 클래스의 인스턴스를 스트림으로 출력 할 수 있습니다.
A x = ...;
std::cout << x << std::endl;
경우에는 당신의 operator<<
욕구는 클래스의 내부를 인쇄하려면 A
정말 당신은 또한 친구 기능으로 선언 할 수는 개인 및 보호 된 멤버에 액세스해야합니다 :
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
이 방법으로 다형성을 허용 할 수도 있습니다.
class Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Base: " << b << "; ";
}
private:
int b;
};
class Derived : public Base {
public:
virtual std::ostream& dump(std::ostream& o) const {
return o << "Derived: " << d << "; ";
}
private:
int d;
}
std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }
C ++ 11에서는 to_string이 표준에 추가되었습니다.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
John이 말한 것의 확장으로 문자열 표현을 추출하여 저장하려면 다음과 같이 std::string
하십시오.
#include <sstream>
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace
std::stringstream
에 위치한 <sstream>
헤더입니다.
질문에 답변되었습니다. 그러나 구체적인 예를 추가하고 싶었습니다.
class Point{
public:
Point(int theX, int theY) :x(theX), y(theY)
{}
// Print the object
friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
int x;
int y;
};
ostream& operator <<(ostream& outputStream, const Point& p){
int posX = p.x;
int posY = p.y;
outputStream << "x="<<posX<<","<<"y="<<posY;
return outputStream;
}
이 예제에서는 운영자 과부하를 이해해야합니다.
참고 URL : https://stackoverflow.com/questions/1549930/c-equivalent-of-javas-tostring
반응형
'Programming' 카테고리의 다른 글
Golang에서 문자열을 분할하여 변수에 할당하는 방법은 무엇입니까? (0) | 2020.06.20 |
---|---|
Mockito에서 Varargs를 올바르게 일치시키는 방법 (0) | 2020.06.20 |
Rust에서 문자열 리터럴과 문자열을 일치시키는 방법은 무엇입니까? (0) | 2020.06.19 |
Android : 활동 수명주기 중에 언제 onCreateOptionsMenu가 호출됩니까? (0) | 2020.06.19 |
C에서 함수형 프로그래밍을위한 도구는 무엇입니까? (0) | 2020.06.19 |