2

look at the following code

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

class C { public: int a; char b; static int c; };

int C::c = 2;

int main(){
C c;
printf("&C::a = %d, &C::b = %d\n", &C::a, &C::b);
cout << "&C::a = " << &C::a << " &C::b = " << &C::b << endl;

getchar();
return 0;
}

the result i get is

&C::a = 0, &C::b = 4

&C::a = 1 &C::b = 1

So why the result of cout is incorrect?

OK, my illustration of this question is ambigious. i am sorry for that. In fact, I want to ask why &C::a and &C::b will cout 1?
As for the result of printf, %d or %p is no matter. They all get the correct result. The difference between them is just %p will output the result in hex format. And I also know that it's better to add a (void*) conversion in the cout. After all, thanks for all of you.

K_Augus
  • 372
  • 2
  • 14
  • 3
    Your code has undefined behaviour, since `%d` expects an `int` argument but you provide a `int (C::*)`. – Kerrek SB Apr 01 '14 at 17:14
  • What do you mean by "it's incorrect"? – Shoe Apr 01 '14 at 17:14
  • @Jefffrey: No, they're constant expressions and fine. – Kerrek SB Apr 01 '14 at 17:15
  • @Jefffrey shouldn't matter for location. Allocation != initialization. – IdeaHat Apr 01 '14 at 17:15
  • Also for cout, gotta cast to void* (void*)&(C::a). Also any compiler worth its salt should say "invalid use of non-static data member C::A) then. If someone can explain to me what &C::a actually does I'd greatly appreciate it, in QT creator it says it is of type `int C::*` and it's value is `&C::a`...I would think it should just barf. – IdeaHat Apr 01 '14 at 17:21
  • @MadScienceDreams It's a pointer-to-member, much like an offset to `this`. E.g. `struct foo { int a; int b; }; foo f; auto p = &foo::a; (f.*p) = 42; p = &foo::b; (f.*p) = 21;` (oh, and it cannot be portably converted to `void*` IIRC) – dyp Apr 01 '14 at 17:27
  • @dyp thanks. Never thought that the same mechanism used for member function could be used for member variables as well. The more you know! That does (interestingly) mean that it can't be port-ably put to cout either. – IdeaHat Apr 01 '14 at 17:38
  • I guess the `cout` version is using implicit conversion to bool? – M.M Apr 01 '14 at 20:37
  • I have just modify my question illustation. I'm sorry for i didn't illustrate it well. And my question is why the result of &C::a and &C::b are both 1? @MattMcNabb, I ever thought of implicit conversion, but I can't recall any implicit conversion useful in such a situation. – K_Augus Apr 02 '14 at 04:46

0 Answers0