Aja*_*kla 0 c++ scope-resolution-operator
Why are we able to call the showA() method without object? But if I use void A::showA(A& x) in the method definition then I have to call it using A's object, why?
#include <iostream>
class A {
public:
int a;
A() { a = 0; }
void showA(A&);
};
void showA(A& x)
{
std::cout << "A::a=" << x.a;
}
int main()
{
A a;
showA(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Why are we able to call the
showA()method without object?
You don't call the member function A::showA, but instead the free function showA. In fact, the member function A::showA(A&) is declared, but never defined, only the free function showA(A&) has a definition.
If you want to call A::showA, you need a definition;
void A::showA(A& x) { /* ... */ }
// ^^^ this makes it a member function definition
Run Code Online (Sandbox Code Playgroud)
and then call it as
A a;
a.showA(a);
Run Code Online (Sandbox Code Playgroud)
(Note that it doesn't make much sense to pass the a instance to A::showA invoked on the identical a instance, but that's another issue).
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |