#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) –