c**********e 发帖数: 2007 | 1 #include
using namespace std;
void f() { cout << "::f" << endl; }
struct P {
void f() { cout << "P::f" << endl; }
};
template
struct X : public T {
void g1() { f(); }
};
int main()
{
X x;
x.g1();
return 0;
}
Choices
a. ::f
b. P::f
c. The program exhibits undefined behavior. |
E*U 发帖数: 2028 | 2 a
【在 c**********e 的大作中提到】 : #include : using namespace std; : void f() { cout << "::f" << endl; } : struct P { : void f() { cout << "P::f" << endl; } : }; : template : struct X : public T { : void g1() { f(); } : };
|
d****p 发帖数: 685 | 3
compiler will try "this->f()" first when looking up the member name f. If it
succeeds, the name lookup completes. So in this case it is P::f()
【在 c**********e 的大作中提到】 : #include : using namespace std; : void f() { cout << "::f" << endl; } : struct P { : void f() { cout << "P::f" << endl; } : }; : template : struct X : public T { : void g1() { f(); } : };
|
I*****y 发帖数: 602 | 4 输出是::f,不是P::f()。
模板基类的方法调用需要显示使用this。
it
【在 d****p 的大作中提到】 : : compiler will try "this->f()" first when looking up the member name f. If it : succeeds, the name lookup completes. So in this case it is P::f()
|
c**********e 发帖数: 2007 | 5 a. ::f
This is the correct behavior. Names in base classes that are not dependent
on template parameters are not considered during the name lookup process.
For this reason the prefix "this->" is sometimes required in template member
functions, or the name will be looked up in the surrounding namespace scope
. (C++ Standard 14.6.2).
b. P::f
According to the standard, this is incorrect. However, your compiler may
produce this result.
My compiler (CC) does produce the wrong answer P::f (b). |
c**********e 发帖数: 2007 | 6 You are right, based on Standard 14.6.2.
【在 I*****y 的大作中提到】 : 输出是::f,不是P::f()。 : 模板基类的方法调用需要显示使用this。 : : it
|
d****p 发帖数: 685 | 7 Cool. Thanks for educating :-)
【在 c**********e 的大作中提到】 : You are right, based on Standard 14.6.2.
|
r****t 发帖数: 10904 | 8 明显是 b ,不会 c++ 的都知道
【在 E*U 的大作中提到】 : a
|
E*U 发帖数: 2028 | 9 u r wrong
【在 r****t 的大作中提到】 : 明显是 b ,不会 c++ 的都知道
|
r****t 发帖数: 10904 | 10 hehe,俺还是不会 c++ 啊。。。想了想,觉得有道理。
【在 E*U 的大作中提到】 : u r wrong
|