使用友元函数时变量被保护

Variable is protected when using friend function

我必须制作一个程序来显示 namesurnameyear 出生的 child。一切都运行良好,除了 friend 函数,它必须访问 private/protected 变量 birth_year 并显示 0 如果他的 birth_year大于2007,否则显示1

代码如下:

#include <iostream>
#include <string.h>

using namespace std;

class child{
protected:

    char name[20],surname[20];
    int birth_year;
public:

    child(char*,char*,int);
    getyear();
    show();
    friend void itsolder();
};

child::child(char* n, char* p, int a)
{

    strcpy(name,n);
    strcpy(surname,p);
    birth_year=a;
}

child::getyear()
{

    return birth_year;
}

child::show()
{

    cout << "Name: " << name << endl;
    cout << "Surname: " << surname << endl;
    cout << "Year of birth: " << birth_year << endl;
}

void itsolder(child&year)
{

    if (year.birth_year>2007)
        cout << "0" << endl;
    else
        cout << "1" << endl;
}

int main()
{

    child c1("Richard", "John", 1997);
    c1.show();
    cout << c1.getyear() << endl;
    itsolder(c1.birth_year)
    return 0;
}

错误如下:

  1. int child::birth_yearprotected;
  2. "within this context" - 是我将条件放入 friend 函数以及我调用它的地方 main();
  3. 从类型 int
  4. 的表达式对类型 child& 的引用的初始化无效

friend void itsolder(); 的声明与

的定义不匹配
void itsolder(child&year)
{
    if (year.birth_year>2007)
        cout << "0" << endl;
    else
        cout << "1" << endl;
}

改为friend void itsolder(child&);并相应传递参数:

itsolder(c1);

我同意@StoryTeller 在他的回答中所写的内容,但除此之外,您的程序自 C++11 起无效。字符串文字的类型为 const char[n],它会衰减为 const char*,但默认情况下,g++clang++ 等编译器出于向后兼容性的原因接受此代码。如果您使用 -pedantic-errors 命令行选项,您将得到编译器错误。

除此之外,缺少 return 类型的 getyear()show() 成员函数。您必须明确指定每个函数的 return 类型。

查看现场演示 here。 观察编译器给出的警告:

g++ -O2 -std=c++11 -Wall -Wextra   main.cpp && ./a.out

main.cpp: In function 'int main()':

main.cpp:53:37: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

     child c1("Richard", "John", 1997);

                                     ^

main.cpp:53:37: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

所以你的正确代码应该是 this.