3

CONCLUSION: Yes, but Intellisense won't like it as of VC++ 11.0.60610.01

I generally don't use friendship, but this time I really need it, and I can't get it to work in Visual Studio 2012. I think it might be an intellisense bug (the code compiles fine) but I just wanted to see if there was something wrong with my code. This reproduces the problem:

class B;

class A
{
public:
    int fun(B b);
};

class B
{
public:
    friend int A::fun(B b);
    B() : member(0) {}
private:
    int member;
};

int A::fun(B b)
{
    return b.member; // Error: B::member is inaccessible.
}

int main()
{
    A a;
    B b;
    std::cout << a.fun(b);
    return 0;
}

The above code compiles fine on codepad but returns an Intellisense error in VS2012. Is there something I'm doing wrong?

4

1 回答 1

2

我认为这是因为您的类上没有构造函数。在这种情况下,它似乎被 IntelliSense 赶上了(这可能确实是一个错误,因为如果您将friend子句更改为 ,它不会抱怨friend class A;),这让您失望:

IntelliSense:成员“B::member”(在第 18 行声明)不可访问

真正的错误(编译器默认将警告视为错误)是这样的:

错误 C4700:使用了未初始化的局部变量“b”

这是我调用的方式:

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    B b;
    std::cout << a.fun(b);
    return 0;
}

B如果您指定自己的默认构造函数来member初始化它,它将构建(并且 IntelliSense 不会抱怨) :

class B
{
public:
    B() : member(0) {}
private:
    int member;
    friend int A::fun(B b);
};
于 2013-10-17T02:20:35.210 回答