Predict the output of below C++ programs.
Question 1
#include<iostream>
using namespace std;
class A {
public:
A(int ii = 0) : i(ii) {}
void show() { cout << "i = " << i << endl;}
private:
int i;
};
class B {
public:
B(int xx) : x(xx) {}
operator A() const { return A(x); }
private:
int x;
};
void g(A a)
{ a.show(); }
int main() {
B b(10);
g(b);
g(20);
return 0;
}
평소에 못보던 연산자 오버로딩이 있는데 B 클래스에 연산자 A()가 오버로딩 되어있다. 이것은 class B가 A로 변환되어야 할 때 불리는 연산자 오버로딩이다. g(b)가 호출될 때 g의 인자 타입은 class A이므로 class B -> class A로 변환이 일어나야 하는데 이때 이 conversion operator가 불려서 class A로 변환이 일어나고 결과적으로 A(x)를 리턴한다.
Reference
https://www.geeksforgeeks.org/output-of-c-program-set-2/?ref=rp
Output of C++ Program | Set 2 - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
Ran into this at work "operator ClassName *". What does this mean?
The class with this code is a reference class for a pointer of ClassName, i.e.: class ClassName; class ClassRef { ClassName* m_class; ... operator ClassName *() const { return m_class...
stackoverflow.com
'공부 > C++ Quiz' 카테고리의 다른 글
가상 함수를 갖고 있는 클래스의 바인딩과 사이즈 예상 문제 (0) | 2022.08.26 |
---|---|
geeksforgeeks Output of C++ Program | Set 1 (0) | 2021.07.07 |