4.1数据语义学-数据成员绑定时机

全局变量和类成员变量同名

#include <iostream>
using namespace std;

string myvar= "I Love China!"; //全局量,字符串型

//定义一个类
class A
{
public:
	int myfunc();
	int myvar; //同全局变量名相同,但类型不同。		
};

int A::myfunc()//成员函数
{
	cout << myvar << endl;  //myvar是类内定义的
	cout << ::myvar.c_str() << endl;  //myvar是全局的
	return myvar; //这里还是A::myvar
}

string myfunc()
{
	return myvar; //这里的myvar是全局的,是string类型
}
int main()
{
	A aobj;
	aobj.myvar = 15;
	aobj.myfunc();
	
	return 1;
}
//结果:
//15
//I Love China!

编译器对 成员函数myfunc的解析,是整个A类定义完毕后才开始;因为只有整个类A定义完毕后,编译器才能看到类A中的myvar,才能根据时机的需要把出现myvar的场合做上述的适当的解释(成员函数中解析成类中的myvar,全局函数中解析成全局的myvar);

全局和类中定义类型别名同名

#include <iostream>
using namespace std;
typedef string mytype;	//全局string别名

//定义一个类
class A
{
public:
	void myfunc(mytype tmpvalue); //mytype是string

private:
	typedef int mytype;//类内int别名
	mytype m_value; //mytype是int	
	
};
//编译阶段报错
//void A::myfunc(mytype tmpvalue) //成员函数形参类型不匹配报错(这里mytype为int型)
//{
//	m_value = tmpvalue;
//}

void myfunc(mytype tmpvalue) //普通函数mytype是string类型
{
	string mvalue = tmpvalue;
}

int main()
{
	return 1;
}

对于成员函数形参:是在编译器第一次遇到整个类型mytype的时候被决定的;所以,mytype第一次遇到的时候,编译器只看到了typedef string mytype,没有看到类中的typedef in mytype;
结论:为了在类中尽早的看到类型mytype,所以这种类型定义语句typedef,一定 要挪到类的最开头定义。那后边的成员函数第一次遇到这个类型mytype的时候,它就本着最近碰到的类型的原则来应用最近碰到的类型。

#include <iostream>
using namespace std;
typedef string mytype;	//全局string别名

//定义一个类
class A
{	
	//放到最前面
	typedef int mytype;//类内int别名
public:
	void myfunc(mytype tmpvalue); //mytype是int

private:	
	mytype m_value; //int	
	
};

void A::myfunc(mytype tmpvalue) //mytype为int型
{
	m_value = tmpvalue;
}

void myfunc(mytype tmpvalue) //普通函数mytype是string类型
{
	string mvalue = tmpvalue;
}

int main()
{
	return 1;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值