趋势笔试题:如何它调用构造函数啊
趋势笔试题:怎么它调用构造函数啊?
#include <stdio.h>
class A{
public:
A(){func(0);};
virtual void func(int data){printf("A1 :%d\n",data);}
virtual void func(int data) const{printf("A2 :%d\n",data);}
void func(char *str){printf("A3 :(%s)\n",str);}
};
class B:public A{
public:
void func(){printf("B1 :%s\n","");}
void func(int data){printf("B2 :%d\n",data);}
void func(char *str){printf("B3 :(%s)\n",str);}
};
int main()
{
A *pA;
B b;
const A *pcA;
pA=&b;
pA->func(1);
pA->func("test");
A().func(1);
pcA=&b;
pcA->func(2);
return 0;
}
A().func(1);
这不是调用构造函数呀?不是不可以显示调用吗?但编译能通过呀,怎么回事?
高手帮帮我!!
------解决方案--------------------
A()是构造一个临时A对象,不是普通得调用构造函数
------解决方案--------------------
“A()”是构造一个无名的临时对象。临时对象可以生存到表达式结束,因此在它上面调用func没有任何问题。
------解决方案--------------------
A() yield a rvalue, which is not necessary to be a c-qualified object in C++. What a confusing!
When I started to learn C++, I always have in mind that a temporary object is const-qualified objct, which meant that A() should yield a const object that could not call non-const member function, but...it turns out I was so wrong.
The deepper I dig into C++, the less I feel I know it.
------解决方案--------------------
其实这里的A()就相当于一个 具体的对象 只是一个无名的对象而已
#include <stdio.h>
class A{
public:
A(){func(0);};
virtual void func(int data){printf("A1 :%d\n",data);}
virtual void func(int data) const{printf("A2 :%d\n",data);}
void func(char *str){printf("A3 :(%s)\n",str);}
};
class B:public A{
public:
void func(){printf("B1 :%s\n","");}
void func(int data){printf("B2 :%d\n",data);}
void func(char *str){printf("B3 :(%s)\n",str);}
};
int main()
{
A *pA;
B b;
const A *pcA;
pA=&b;
pA->func(1);
pA->func("test");
A().func(1);
pcA=&b;
pcA->func(2);
return 0;
}
A().func(1);
这不是调用构造函数呀?不是不可以显示调用吗?但编译能通过呀,怎么回事?
高手帮帮我!!
------解决方案--------------------
A()是构造一个临时A对象,不是普通得调用构造函数
------解决方案--------------------
“A()”是构造一个无名的临时对象。临时对象可以生存到表达式结束,因此在它上面调用func没有任何问题。
------解决方案--------------------
A() yield a rvalue, which is not necessary to be a c-qualified object in C++. What a confusing!
When I started to learn C++, I always have in mind that a temporary object is const-qualified objct, which meant that A() should yield a const object that could not call non-const member function, but...it turns out I was so wrong.
The deepper I dig into C++, the less I feel I know it.
------解决方案--------------------
其实这里的A()就相当于一个 具体的对象 只是一个无名的对象而已