【发布时间】:2013-08-28 07:48:10
【问题描述】:
我是 C++ 的新手。我写了一个简单的程序来实现友元函数的使用。代码如下:-
#include<iostream>
using namespace std;
class one
{
private:
int age;
public:
one()
{
age=1;
}
void setData(int num)
{
age=num;
}
friend int returnOne()
{
return age;
}
};
class two
{
private:
int roll;
public:
two()
{
roll=0;
}
void setData(int num)
{
roll=num;
}
friend int returnTwo()
{
return roll;
}
};
int main()
{
one a;
two b;
cout<<a.returnOne()<<endl<<b.returnTwo()<<endl;
}
我在 c++ 中遇到以下错误。
friend.cpp: In function ‘int returnOne()’:
friend.cpp:8:6: error: invalid use of non-static data member ‘one::age’
friend.cpp:20:9: error: from this location
friend.cpp: In function ‘int returnTwo()’:
friend.cpp:27:6: error: invalid use of non-static data member ‘two::roll’
friend.cpp:39:9: error: from this location
friend.cpp: In function ‘int main()’:
friend.cpp:47:10: error: ‘class one’ has no member named ‘returnOne’
friend.cpp:47:31: error: ‘class two’ has no member named ‘returnTwo’
编辑 谢谢。它解决了这个问题。
但是现在它让我想到另一个问题。friend 关键字现在是不是损害了使用private 的目的,因为现在任何类或函数都可以简单地使用friend 函数来访问私有数据成员。如果是,他们我们可以简单地将数据成员声明为public 而不是private。使用private 有什么特别之处?
【问题讨论】:
-
这个问题的标题立刻让我想起了 Joe Cocker 的一首歌。 :-}
-
@FrerichRaabe 你是说披头士乐队?
-
@juanchopanza:你是对的!我总是想起乔科克的版本。既然你提到了,我记得这首歌是专门为林戈写的,因为他只能选择几个(五个?)不同的音调。不管怎样,我分心了……
标签: c++ class oop friend friend-function