c++ - Friend Function calling Static Members of Derived Classes. Not getting expected output -



c++ - Friend Function calling Static Members of Derived Classes. Not getting expected output -

my first post here :)

i having problem next c++ code. have abc class a, , 2 derived classes b , c. of them have static fellow member called id:

using std::cout; class { private: friend int bar(a& a); static const int id = 1; virtual void foo() = 0; }; class b : public { private : friend int bar(a& a); static const int id = 2; void foo() { /*do something*/ } }; class c : public { private: friend int bar(a& a); static const int id = 3; void foo() { /*do something*/ } }; int bar(a& a) { homecoming a.id; } int main() { b b; c c; cout << bar(b) << "\n"; cout << bar(c) << "\n"; homecoming 0; }

i expecting code print out 2 , 3 - rather prints out 1 , 1 (bar() using a::id). doing wrong? ideas?

based on comments below, final code using. works, love hear more thoughts :)

#include <iostream> using std::cout; class { private: virtual void foo() = 0; }; class b : public { private: template <typename t> friend int bar(t& t); static const int id = 2; void foo() { /*do something*/ } }; class c : public { private: template <typename t> friend int bar(t& t); static const int id = 3; void foo() { /*do something*/ } }; template <typename t> int bar(t& t) { homecoming t.id; } int main() { b b; c c; cout << bar(b) << "\n"; cout << bar(c) << "\n"; homecoming 0; }

is there way avoid writing int foo() { homecoming id; } derived classes?

yes, using templates. example:

template <typename t> int foo (t& x) { homecoming x.id; }

however, if id private, doesn't cut down code much.

c++ static friend

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -