#include <iostream>
class Test {
public:
int i;
void print()
{
std::cout << "Hello" << std::endl;
}
};
int main()
{
class Test *p = NULL;
p->print();
(*p).print();
}
Output:
Hello
Hello
我的理解是對象的方法和成員變量都存儲在不同的內存位置,但是當p
被指定爲NULL
如何能夠解決調用Test::print()
C++概念Acessing公共方法
Test6:~ 1001> g++ --version
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Test6:~ 1002> g++ manoj.cpp
Test6:~ 1003> ./a.out
Hello
Hello
Test6:~ 1004> cat manoj.cpp
#include <iostream>
class Test {
public:
int i;
void print()
{
std::cout << "Hello" << std::endl;
}
};
int main()
{
class Test *p = NULL;
p->print();
(*p).print();
}
Test6:~ 1005>
我猜想這是未定義的行爲,而且你很幸運它的工作。 [主叫通過NULL類指針類方法]的 –
可能重複(http://stackoverflow.com/questions/2505328/calling-class-method-through-null-class-pointer) –