我想知道朋友函数是否可以在不使用a的情况下更改类中的私有数据
指针和发送对象.
我的意思是朋友功能可以像成员函数那样访问吗?
例如:
class myinfo {
private:
char name[20];
int id;
float income;
public:
void showInfo(void);
myinfo(void);
friend void updateInfo(myinfo);
int main ( ) {
myinfo j;
updateInfo(j); // calling the friend function
return 0;
}
void updateInfo(myinfo c) {
strcat(c.name, ":updated");
c.id++;
c.income += 1.1;
Run Code Online (Sandbox Code Playgroud)
是的,但不是你写的方式...如果你想让函数修改传入的对象,接受引用而不是值...
看来你还没有学过c ++中的引用.
// Declaration of function in class
friend void updateInfo(myinfo&);
Run Code Online (Sandbox Code Playgroud)
履行
void updateInfo(myinfo& c)
{
strcat(c.name, ":updated"); // now modifying passed in instance of c.
c.id++;
c.income += 1.1;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句.在附注中,更喜欢使用std::string并且也学习三级规则(特别是对于非平凡的类,例如这个).