免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4413 | 回复: 2
打印 上一主题 下一主题

[C++] (请教)继承普通类和模板类的一个问题(关于类作用域) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-07-08 16:19 |只看该作者 |倒序浏览
请看代码

1:  普通类---------------------------------
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;

class A
{
    int a;
public:
    A(int aa = 19) : a(aa){ }
    int get_value_A() const { return a; }
};

class B: public A
{
public:
    B() : A(40) { }

    int get_value()
    {
        return get_value_A();
    }
};

int main(int argc, char* argv[])
{
    B b;
    printf("%d\n", b.get_value());

    return 0;
}

2: 模板类 -------------------------头文件----inherit_tem.h-------
#ifndef _AAAAAAAAAAA_
#define _AAAAAAAAAAA_
#include <iostream>
using namespace std;
template<class T, int ret = 6>
class A
{
    T a;
    int b;
public:
    A(T& aa = 0) : a(aa), b(ret){ }
    void print() const
    {
        cout << "A: " << a << endl;
    }
    int count() const{ return b; }
};


template<class T>
class B : public A<T>
{
public:
    B(T& aa) : A<T>(aa){ }
    void Bprint() const
    {
        A<T>::print();
    }
    void print_int() const
    {
        cout << "print_int " << A<T>::count() << endl;
    }
};

#endif
-------------------源文件------------------
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "inherit_tem.h"

using namespace std;

int main(int argc, char* argv[])
{
    int bb = 3;
    B<int> b(bb);
    b.Bprint();
    b.print_int();

    return 0;
}
.....................................................................
........................................................................
在继承模板类中 子类调用父类函数 为什么必须要加 父类作用域 A<T>::  否则编译不过  ,而 普通类继承却不用加父类作用域
请教  我用的是g++ 4.4.5   GNU project C++ compiler

论坛徽章:
0
2 [报告]
发表于 2011-07-09 09:35 |只看该作者
这的确是个问题啊

论坛徽章:
0
3 [报告]
发表于 2011-07-09 15:03 |只看该作者
引用一下我博客上某篇文章的一段话:
在模板定义中,出现的名字可分为三类:
    (1)模板自身的名字和在模板中声明的名字;
    (2)依赖于模板参数的名字(dependent name);
    (3)不依赖于模板参数且在模板定义中可见的名字(non-dependent name)。
在名字解析时,第二类名字和第三类名字的解析绑定不同,被称为二段式名字查找规则。具体而言,对于dependent name,由于模板参数类型未知,因此其只能在模板实例化的上下文中才能进行名字查找与绑定。对于non-dependent name,其在名字出现的地方采用一般的名字查找规则。

http://blogold.chinaunix.net/u/18517/showart_454524.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP