【问题标题】:Variable is protected when using friend function使用友元函数时变量受保护
【发布时间】:2017-11-30 02:51:33
【问题描述】:

我必须制作一个程序来显示孩子出生时的namesurnameyear。一切正常,除了friend 函数,它必须访问private/protected 变量birth_year 并显示0,如果他的birth_year 大于2007,否则显示@ 987654331@.

代码如下:

#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. “在此上下文中” - 是我将条件放入 friend 函数的位置,我将其调用到 main() 中;
  3. 来自int 类型表达式的child&amp; 类型引用的初始化无效

【问题讨论】:

  • child::getyear() 是错误的(如果这是为了引入函数体,必须事先指定返回类型)

标签: c++ function private protected


【解决方案1】:

friend void itsolder(); 的声明与

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

将其更改为friend void itsolder(child&amp;); 并相应地传递参数:

itsolder(c1);

【讨论】:

    【解决方案2】:

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

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

    查看现场演示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

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-26
      • 2011-08-02
      • 1970-01-01
      • 2016-03-08
      • 2010-09-30
      • 1970-01-01
      相关资源
      最近更新 更多