这可能吗?我们可以声明一个没有参数的朋友函数吗?
class sample {
private:
int x;
public:
friend void fun();
};
friend
函数没有参数!
在不可能我看来
因为友元函数不是类的“成员” 所以我们不能用类对象
像拨打:
sample s;
s.fun();
这可能吗?我们可以声明一个没有参数的朋友函数吗?
class sample {
private:
int x;
public:
friend void fun();
};
friend
函数没有参数!
在不可能我看来
因为友元函数不是类的“成员” 所以我们不能用类对象
像拨打:
sample s;
s.fun();
是的,你可以。这可能有很多原因,例如访问私有静态成员,或者可能存在全局实例sample
。 fun
也可能创建sample
的实例并获取其私有。
工作示例的功能创建实例,做的东西吧:
#include <iostream>
class sample {
private:
int x;
public:
friend void fun();
};
void fun()
{
sample s;
s.x = 555555555;
std::cout << s.x;
}
int main(){
fun();
return 0;
}
例如与全局实例:
#include <iostream>
#include <string>
class sample {
private:
int x;
public:
friend void fun();
};
sample s;
void fun()
{
s.x = 555555555;
std::cout << s.x;
}
int main(){
fun();
return 0;
}
例如私人静态成员:
#include <iostream>
#include <string>
class sample {
private:
int x;
static const int w = 55;
public:
friend void fun();
};
void fun()
{
std::cout << sample::w;
}
int main(){
fun();
return 0;
}
请举个例子吗? –
@DixitSingla补充示例 –
好的先生 谢谢 –
是的,您可以:
void fun()
{
sample s;
s.x++; // OK, fun() is a friend of sample
}
或
sample globalSample; // yikes, a global variable
void fun()
{
int i = globalSample.x; // OK, fun() is a friend of sample
}
是的,但对于变量,你将需要它们是全球性的。在你的情况下,类型为sample
的全局对象。或可能在内部创建函数的定义fun()
。
sample globalObject;
void fun()
{
globalObject.x++; //this will work as fun() is friend function of sample.
}
除非函数内部创建了一个'sample'对象... – maditya
有可能没有参数的朋友功能。你需要另一种方法来访问类样本的对象。不要忘记,朋友功能还允许您访问类样本的私有静态变量,以防您需要时
当然这是可能的。你好奇你为什么会这样做。例如,它可以访问静态私有成员变量。或者它可以访问它通过某种方式获得的对象的私有成员(单身,全局(对象的容器),...)
这是可能,有一个朋友的乐趣没有参数的情况下。它很少使用。
sample s;
s.fun();
无论如何,这将无法正常工作,因为C++中的“友谊”只是提升对私人/受保护成员的访问限制。朋友不是班级成员,所以你无法调用s.fun()。
但是,您可以声明一个像你所描述的朋友功能,并从该功能,你将有权访问示例类的私人成员。
友方法可能是有用的,因为对私有/受保护数据成员的访问仅限于指定的方法。这个方法有参数或返回类型无关紧要。
template <class T>
class CLinkedListNode {
public:
CLinkedListNode(CLinkedList<T>* Parent) : _Parent(Parent) {
}
protected:
CLinkedListNode * _Next;
T _Data;
CLinkedList<T>* _Parent;
friend CLinkedListNode<T>* CLinkedList<T>::find(); // Only CLinkedList<T>::find() may access data members
friend void sort(); // All sort methods may access data members
};
所以,想象一下还有一类CLinkedList其find()
方法是能够访问CLinkedListNode的所有数据成员。
template <class T>
class CLinkedList {
// ...
CLinkedListNode<T>* find() {
CLinkedListNode<T>* Node = new CLinkedListNode<T>(this);
CLinkedListNode<T>* Find = Node->_Next;
while (Find->_Next) {
// Do something
Find = Find->_Next;
}
// ...
return Node;
}
};
@sehe:为什么?还有* conformist *朋友。 – Nawaz
@Nawaz [在这里让我解释](http://i.imgur.com/axJmn.gif) –
@ P0W你是什么意思*“它会有道理”*? –