关于C++友元的一个问题
我在网上看到一个关于友元类的程序,自己修改了一下,加入了一个继承类,分别在unix和VC下编译却得到了2种结果,一时有些迷惑,请各位专家赐教原因。
代码如下:
//filename:frdclass.cpp
//to use friend class to call base and his son class.
#include <iostream.h>
#include <string.h>
class Internet;
class Country //Base class
{
public:
Country()
{
strcpy(cname, "I 'm from Guangdong ");
cout < < "Country Constructor is called. " < <endl;
}
friend class Internet;//友类的声明
protected:
char cname[100];
};
class Province:public Country
{
public:
Province()
{
strcat(cname, ",shenzhen ");
cout < < "Province Constructor is called. " < <endl;
}
friend class Internet;//友元类的声明?
protected:
char cname[300];
};
class Internet //友元类定义
{
public:
Internet(char *name,char *address)
{
strcpy(Internet::name,name);
strcpy(Internet::address,address);
cout < < "internet constructor " < < endl ;
}
void Editcname(Country &temp);
protected:
char name[20];
char address[20];
};
void Internet::Editcname(Country &temp)
{
strcat(temp.cname, "of PRC. "); //把of PRC加到cname数组后面
cout < < temp.cname < <endl;
}
void main()
{
Internet a( "百度 ", "www.baidu.com ");
Country b;
Province c;
a.Editcname(b);
a.Editcname(c);
}
在unix下CC编译后输出结果:
internet constructor
Country Constructor is called.
Country Constructor is called.
Province Constructor is called.
I 'm from Guangdong of PRC.
I 'm from Guangdong of PRC.
在VC6编译后输出的结果:
internet constructor
Country Constructor is called.
Country Constructor is called.
Province Constructor is caled.
I 'm from Guangdong ,shenzhe of PRC.
I 'm from Guangdong of PRC.
而我的本意是输出:
internet constructor
Country Constructor is called.
Country Constructor is called.
Province Constructor is caled.
I 'm from Guangdong of PRC.
I 'm from Guangdong ,shenzhe of PRC.
请问怎样才能达到这个目的?
[解决办法]
class Province:public Country
{
public:
.....................
protected:
// 注释掉这个: char cname[300];
};
[解决办法]
class Province:public Country
{
public:
Province()
{
strcat(cname, ",shenzhen "); //strcat? cname中的内容呢
cout < < "Province Constructor is called. " < <endl;
cout < <cname < <endl;
}
...
楼主是想的 cname 由基类中构造了么?
概念问题 ...
