作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我的第一篇文章:)
我在使用以下 C++ 代码时遇到问题。我有一个 ABC 类 A 和两个派生类 B 和 C。它们都有一个名为 id 的静态成员:
using std::cout;
class A
{
private:
friend int bar(A& a);
static const int id = 1;
virtual void foo() = 0;
};
class B : public A
{
private :
friend int bar(A& a);
static const int id = 2;
void foo() { /*Do something*/ }
};
class C : public A
{
private:
friend int bar(A& a);
static const int id = 3;
void foo() { /*Do something*/ }
};
int bar(A& a)
{
return a.id;
}
int main()
{
B b;
C c;
cout << bar(b) << "\n";
cout << bar(c) << "\n";
return 0;
}
我原以为这段代码会打印出 2 和 3,但它打印出了 1 和 1(bar() 始终使用 A::id)。我究竟做错了什么?有什么想法吗?
根据下面的评论,这是我使用的最终代码。它有效,但很想听到更多想法:)
#include <iostream>
using std::cout;
class A
{
private:
virtual void foo() = 0;
};
class B : public A
{
private:
template <typename T>
friend int bar(T& t);
static const int id = 2;
void foo() { /*do something*/ }
};
class C : public A
{
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)
{
return t.id;
}
int main()
{
B b;
C c;
cout << bar(b) << "\n";
cout << bar(c) << "\n";
return 0;
}
最佳答案
a.id
将在编译时定义为 A::id
。您需要在类 A
中定义一个虚拟成员(非静态)函数,并在 B
和 C
中覆盖它以返回它们各自的id
并在 bar
中调用此函数。
关于c++ - 友元函数调用派生类的静态成员。没有得到预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934982/
我是一名优秀的程序员,十分优秀!