1

我的代码有什么问题?

我尝试在 GNU G++ 环境中编译以下代码,但出现以下错误:

friend2.cpp:30: 错误: 不完整类型“结构二”的无效使用
friend2.cpp:5:错误:“结构二”的前向声明
friend2.cpp:在成员函数“int two::accessboth(one)”中:
friend2.cpp:24: 错误: 'int one::data1' 是私有的
friend2.cpp:55:错误:在此上下文中
#include <iostream>
using namespace std;

class two;

class one
{
    private:
        int data1;
    public:
        one()
        {
            data1 = 100;
        }

        friend int two::accessboth(one a);
};

class two
{
    private:
        int data2;

    public:
        two()
        {
            data2 = 200;
        }

        int accessboth(one a);
};

int two::accessboth(one a)
{
    return (a.data1 + (*this).data2);
}

int main()
{
    one a;
    two b;
    cout << b.accessboth(a);
    return 0;
}
4

1 回答 1

9

成员函数必须首先在其类中声明(而不是在友元声明中)。这必须意味着在朋友声明之前,您应该定义它的类 - 仅仅前向声明是不够的。

class one;

class two
 {
    private:
  int data2;
    public:
  two()
  {
    data2 = 200;
  }
 // this goes fine, because the function is not yet defined. 
 int accessboth(one a);
 };

class one
 {
     private:
  int data1;
    public:
  one()
  {
    data1 = 100;
  }
    friend int two::accessboth(one a);
 };

 // don't forget "inline" if the definition is in a header. 
 inline int two::accessboth(one a) {
  return (a.data1 + (*this).data2);
 }
于 2009-12-27T16:05:54.997 回答