简体   繁体   English

答案并不清楚c ++

[英]The answer is not clear c++

Here is a test question: 这是一个测试问题:

Consider the following code: 请考虑以下代码:

class A {
    typedef int I; // private member
    I f();
    friend I g(I);
    static I x;
};

Which of the following are valid: 以下哪项有效:

a. A::I A::f() { return 0; }
b. A::I g(A::I p = A::x);
c. A::I g(A::I p) { return 0; }
d. A::I A::x = 0;

Answer to this question is considered correct only the first version (a.), but why? 这个问题的答案只被认为是正确的第一个版本(a。),但为什么? All them are valid in my opinion. 在我看来,它们都是有效的。 Even tested all they compile successfully. 甚至测试了所有他们成功编译。 Why only the first answer is correct? 为什么只有第一个答案是正确的?

Whoever wrote the original answer to the test is wrong. 谁写了测试的原始答案是错误的。

  • This example comes (exactly) from the C++ standard itself , section § 11/7, [class.access], and has been copied by the one who wrote the "test" 这个例子(确切地)来自C ++标准本身 ,第11/7节,[class.access],并且被写了“test”的人复制了。

The example goes even further in the standard, with templates (I'll omit them here): 该示例在标准中更进一步,使用模板(我将在此省略它们):

      class A {
          typedef int I;      // private member
          I f();
          friend I g(I);
          static I x;
      };

      A::I A::f() { return 0; }
      A::I g(A::I p = A::x);
      A::I g(A::I p) { return 0; }
      A::I A::x = 0;
  • Quoting the standard for the explanation: 引用解释标准:

Here, all the uses of A::I are well-formed because A::f and A::x are members of class A and g is a friend of class A. This implies, for example, that access checking on the first use of A::I must be deferred until it is determined that this use of A::I is as the return type of a member of class A. ] 这里, A::I所有用法都是格式良好的,因为A::fA::x是A类的成员,而g是A类的朋友。这意味着,例如,对第一个进行访问检查必须推迟使用A::I直到确定A::I这种用法作为A::I类成员的返回类型。

They are all valid C++. 它们都是有效的C ++。

Here is the exact code, it is an example from the standard itself: 这是确切的代码,它是标准本身的一个例子:

http://www.open-std.org/jtc1/sc22/open/n2356/access.html http://www.open-std.org/jtc1/sc22/open/n2356/access.html

This is how I parse them: 这是我解析它们的方式:

a. A::I A::f() { return 0; } // defines A::f() which was previously prototyped

b. A::I g(A::I p = A::x);    // declares prototype g(A::I), but doesn't define it

c. A::I g(A::I p) { return 0; } // defines g(A::I)

d. A::I A::x = 0; // defines static storage for A::x which was previously declared in A

These all compile, both individually, and collectively. 这些都是单独和集体编译的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM