首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于友元函数,程序的异常原因?

2013-07-08 
【求助】关于友元函数,程序的错误原因????#include iostreamusing namespace stdnamespace Test{class A{

【求助】关于友元函数,程序的错误原因????

#include <iostream>

using namespace std;

namespace Test{
class A{
public:
friend void TestFn1(const A &a){};
};
void TestFn2(const A &a){};
}
class B{
public:
operator Test::A(){return Test::A();}
};
using namespace Test;
void TestFn3(const A &a){}

void main(){
B obj;
TestFn1(obj);
TestFn2(obj);//不需要通过对象调用,因为有using namespace Test;
TestFn3(obj);
}

[解决办法]
引用:
operator Test::A()是定义了一个转换操作符。。其实就是可以将B类对象用在需要Test::A类对象的地方。。
另外你的代码需要改一下。。

#include <iostream>

using namespace std;

namespace Test{
class A{
public:
friend void TestFn1(const A &a);
};
void TestFn1(const A &a){}//把定义放在类外。。
void TestFn2(const A &a){}
}
class B{
public:
operator Test::A(){return Test::A();}
};
using namespace Test;
void TestFn3(const A &a){}

void main(){
B obj;
TestFn1(obj);
TestFn2(obj);//不需要通过对象调用,因为有using namespace Test;
TestFn3(obj);
}

这并不是问题的本质,
下面这段话来自MSDN: 

'function' candidate function(s) not accessible 


A friend function defined in a class is not supposed to be treated as if it were defined and declared in the global namespace scope. It can, however, be found by argument-dependent lookup. 

例子:和你给的基本一样 

C/C++ code // C3767e.cpp
namespace N {
   class C {
      friend void FriendFunc() {}
      friend void AnotherFriendFunc(C* c) {}
   };
}

int main() {


   using namespace N;
   FriendFunc();   // 直接编译错误 C3767 error
   C* pC = new C();
   AnotherFriendFunc(pC);   // found via argument-dependent lookup
}
[解决办法]

引用:
Quote: 引用:

operator Test::A()是定义了一个转换操作符。。其实就是可以将B类对象用在需要Test::A类对象的地方。。
另外你的代码需要改一下。。

#include <iostream>

using namespace std;

namespace Test{
class A{
public:
friend void TestFn1(const A &a);
};
void TestFn1(const A &a){}//把定义放在类外。。
void TestFn2(const A &a){}
}
class B{
public:
operator Test::A(){return Test::A();}
};
using namespace Test;
void TestFn3(const A &a){}

void main(){
B obj;
TestFn1(obj);
TestFn2(obj);//不需要通过对象调用,因为有using namespace Test;
TestFn3(obj);
}

这并不是问题的本质,
下面这段话来自MSDN: 

'function' candidate function(s) not accessible 


A friend function defined in a class is not supposed to be treated as if it were defined and declared in the global namespace scope. It can, however, be found by argument-dependent lookup. 

例子:和你给的基本一样 

C/C++ code // C3767e.cpp
namespace N {
   class C {
      friend void FriendFunc() {}
      friend void AnotherFriendFunc(C* c) {}
   };
}

int main() {
   using namespace N;
   FriendFunc();   // 直接编译错误 C3767 error
   C* pC = new C();
   AnotherFriendFunc(pC);   // found via argument-dependent lookup
}
这个应该是正解
顺便,类外再声明一下FriendFunc();就能访问到了

热点排行