类指针即使没有初始化,也可以正常访问其成员函数吗?该如何解决
类指针即使没有初始化,也可以正常访问其成员函数吗?
今天看到朋友写的一份代码,很奇怪:
#include <iostream>
/*
Compile Env: Dev cpp 4.9.9.2
*/
class XCircle
{
public:
void displayIt()
{ std::cout < < "XCircle Display\n "; }
~XCircle() {}
private:
XCircle() {}
};
class Shape
{
public:
void display();
Shape() {}
~Shape() {}
};
class Adapter:public Shape
{
private:
XCircle *xc;
public:
Adapter()
{
}
void display()
{
xc-> displayIt();
//****这里**** xc没有任何初始化操作,但是可以访问其成员函数
}
~Adapter()
{
}
};
int main()
{
Adapter ad;
ad.display();
std::getchar();
}
哪位有研究过吗?我想知道是什么原因.
------解决方案--------------------
那样看看是什么样子的成员函数了
要是成员函数没有访问和读取成员变量就没有问题.
------解决方案--------------------
http://community.****.net/Expert/topic/5526/5526033.xml?temp=.4985926
------解决方案--------------------
只要函数里没有用到成员变量是可以的
比如
class T
{
public :
void a() {cout < < "a " < <endl;}
void b() {cout < <date < <endl; }
private :
int date;
}
void main()
{
T* p = NULL;
p-> a(); // 正常
p-> b(); // 错去,当机
}
------解决方案--------------------
To 楼主:
其实在你的Adapter类中可以不显式地声明XCircle *xc;
而在display方法中做这样实现:
void Adaptor::display()
{
((XCircle*)this)-> displayIt();
}
这样,Adaptor类与XCircle类之间只是相识关系。
------解决方案--------------------
displayIt名称修饰类似为全局函数displayIt@xCircle(xCircle* this_);
xc-> displayIt()转化为调用全局函数displayIt@xCircle(xc);
故如果没有使用xc,就可以成立,否则异常.
最后的说明是,这样的程序是错误的,既然displayIt没用到xc的成员变量,为什么定义为成员函数呢?
void displayIt();
这样的函数原型声明说明了:
1、必然直接或间接的使用了xc的成员变量.
2、调用前和调用后xc状态必然不同,因为函数没有const修饰,表示改变状态
3、可以接受C风格的可变参数,应为没有void参数说明(即void displayIt(void);)
4、函数名称错误,一般显示不用改变状态,照相能改变身高、体型么?
今天看到朋友写的一份代码,很奇怪:
#include <iostream>
/*
Compile Env: Dev cpp 4.9.9.2
*/
class XCircle
{
public:
void displayIt()
{ std::cout < < "XCircle Display\n "; }
~XCircle() {}
private:
XCircle() {}
};
class Shape
{
public:
void display();
Shape() {}
~Shape() {}
};
class Adapter:public Shape
{
private:
XCircle *xc;
public:
Adapter()
{
}
void display()
{
xc-> displayIt();
//****这里**** xc没有任何初始化操作,但是可以访问其成员函数
}
~Adapter()
{
}
};
int main()
{
Adapter ad;
ad.display();
std::getchar();
}
哪位有研究过吗?我想知道是什么原因.
------解决方案--------------------
那样看看是什么样子的成员函数了
要是成员函数没有访问和读取成员变量就没有问题.
------解决方案--------------------
http://community.****.net/Expert/topic/5526/5526033.xml?temp=.4985926
------解决方案--------------------
只要函数里没有用到成员变量是可以的
比如
class T
{
public :
void a() {cout < < "a " < <endl;}
void b() {cout < <date < <endl; }
private :
int date;
}
void main()
{
T* p = NULL;
p-> a(); // 正常
p-> b(); // 错去,当机
}
------解决方案--------------------
To 楼主:
其实在你的Adapter类中可以不显式地声明XCircle *xc;
而在display方法中做这样实现:
void Adaptor::display()
{
((XCircle*)this)-> displayIt();
}
这样,Adaptor类与XCircle类之间只是相识关系。
------解决方案--------------------
displayIt名称修饰类似为全局函数displayIt@xCircle(xCircle* this_);
xc-> displayIt()转化为调用全局函数displayIt@xCircle(xc);
故如果没有使用xc,就可以成立,否则异常.
最后的说明是,这样的程序是错误的,既然displayIt没用到xc的成员变量,为什么定义为成员函数呢?
void displayIt();
这样的函数原型声明说明了:
1、必然直接或间接的使用了xc的成员变量.
2、调用前和调用后xc状态必然不同,因为函数没有const修饰,表示改变状态
3、可以接受C风格的可变参数,应为没有void参数说明(即void displayIt(void);)
4、函数名称错误,一般显示不用改变状态,照相能改变身高、体型么?