免费注册 查看新帖 |

Chinaunix

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

[C++] 《C++程序设计语言(特别版)》第11章的一个问题,关于内部类 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-11 13:39 |只看该作者 |倒序浏览
《TC++PL》第11章最后实现了一个String类,其中用到了类内部定义的类和结构。大致结构类似于下面的小程序:
#include <stdio.h>

class T
{
    public:
        T(int num) { s = new S(num); }
        void print() { printf("%d\n", s -> number); }
    private:
        struct S;
        S *s;
};

struct T::S
{
    int number;
    S(int num) : number(num) {}
    private:
        S(const S&);
        S& operator=(const S&);
};

int main()
{
    T t(3);
    t.print();
    return 0;
}



出现下面错误:

6:error:invalid use of incomplete type 'struct T::S'
9:error:forward declaration of 'struct T:S:'
7:error:invalid use of incomplete type 'struct T::S'
9:error:forward declaration of 'struct T:S:'


如果把结构体S的内容在类T的声明中展开,就可以编译通过,但是《TC++PL》的程序的确是像上面的程序那样用内部类的,是因为编译器不支持书上这种语法的原因么?

论坛徽章:
0
2 [报告]
发表于 2009-08-11 14:37 |只看该作者

回复 #1 lazywrite 的帖子

《C++ Primer》里面讲了:在没有看到嵌套类的定义之前,外围类只能声明嵌套类的引用或者指针。

想想也是哦,我都不晓得你里面是什么东东,你就要我new,我new个铲铲哦~~~~~

论坛徽章:
2
青铜圣斗士
日期:2015-11-26 06:15:59数据库技术版块每日发帖之星
日期:2016-07-24 06:20:00
3 [报告]
发表于 2009-08-11 17:32 |只看该作者

回复 #1 lazywrite 的帖子

#include <stdio.h>

class T
{
    public:
        T(int num);
        void print();
    private:
        struct S;
        S *s;
};

struct T::S
{
    int number;
    S(int num) : number(num) {}
    private:
        S(const S&);
        S& operator=(const S&);
};

T::T(int num) { s = new S(num); }
void T::print() { printf("%d\n", s -> number); }

int main()
{
    T t(3);
    t.print();
    return 0;
}


书籍上的代码因为篇幅或者排版关系,并不一定就能编译, 而是不像伪代码的伪代码。
btw: lz是重庆的?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP