游戏开发论坛

 找回密码
 立即注册
搜索
查看: 2556|回复: 6

关于成员函数const 后缀修饰的奇怪现象

[复制链接]

38

主题

275

帖子

281

积分

中级会员

Rank: 3Rank: 3

积分
281
QQ
发表于 2006-3-6 23:49:00 | 显示全部楼层 |阅读模式
大家知道,声明成员函数时,末尾加const修饰,表示在成员函数内不得改变该对象的任何数据。

但是我写了以下这个程序时,出现了我觉得很奇怪的现象,看程序:
#include <iostream>
#include <stdlib.h>
#define  PAUSE        system("pause")

using namespace std;

class CDemo
{
        private:
                int m_a;
               
        public:
               
                int Get_m_a() const;
               
                void Set_m_a(int a);
               
};

int CDemo::Get_m_a() const
{
        CDemo::m_a=10;
        return m_a;
}

void CDemo::Set_m_a(int a)
{
        CDemo::m_a=a;
       

}


int main()

{

        CDemo m;
        m.Set_m_a(20);
       
        int a=m.Get_m_a();
       
        cout << "a=" <<a<<endl;
       
        PAUSE;
       
        return 0;
       
}



上面代码居然能够通过编译~~但是当我把Get_m_a()中的 CDemo::m_a=10;改位 m_a=10; 后,情况才变的正常-----通不过编译,因为Get_m_a不能修改其对象的成员变量~~
奇怪啊~~

38

主题

275

帖子

281

积分

中级会员

Rank: 3Rank: 3

积分
281
QQ
 楼主| 发表于 2006-3-7 00:02:00 | 显示全部楼层

Re:关于成员函数const 后缀修饰的奇怪现象

~~我用的编译器是Dev-C++~~
  后来我在VC6下调试这个程序,结果让我非常吃惊~~即使加CDemo::m_a也无法通过编译~这个结果才是预料之中的~~真的是激动啊~
  从这个例子我们看出,好象是VC6支持C++比GCC好~~真的非常的汗~~大家不是说了嘛~~GCC支持C++比VC好啊~~郁闷~~~这是怎么回事~~牛人请指点~

2

主题

182

帖子

182

积分

注册会员

Rank: 2

积分
182
发表于 2006-3-7 00:53:00 | 显示全部楼层

Re:关于成员函数const 后缀修饰的奇怪现象

错误是难免的。。。

2

主题

182

帖子

182

积分

注册会员

Rank: 2

积分
182
发表于 2006-3-7 00:56:00 | 显示全部楼层

Re:关于成员函数const 后缀修饰的奇怪现象

C:\>g++ test.cpp
test.cpp:1:22: warning: extra tokens at end of #include directive
test.cpp: In member function `int CDemo::Get_m_a() const':
test.cpp:15: error: assignment of data-member `CDemo::m_a' in read-only structur
e
test.cpp: In function `int main()':
test.cpp:35: error: `PAUSE' undeclared (first use this function)
test.cpp:35: error: (Each undeclared identifier is reported only once for each f
unction it appears in.)

2

主题

182

帖子

182

积分

注册会员

Rank: 2

积分
182
发表于 2006-3-7 00:56:00 | 显示全部楼层

Re:关于成员函数const 后缀修饰的奇怪现象

这是我的编译输出,显然你的gcc版本有问题。

2

主题

182

帖子

182

积分

注册会员

Rank: 2

积分
182
发表于 2006-3-7 00:56:00 | 显示全部楼层

Re:关于成员函数const 后缀修饰的奇怪现象

C:\>g++ --version
g++ (GCC) 3.4.4 (mingw special)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

38

主题

275

帖子

281

积分

中级会员

Rank: 3Rank: 3

积分
281
QQ
 楼主| 发表于 2006-3-7 01:05:00 | 显示全部楼层

Re:关于成员函数const 后缀修饰的奇怪现象

~~恩~~由于在VC下正常,我直接就否定了我的 那个Dev-C++,我一看它的版本4。9。6。0--于是我到网上下了个4。9。9。2的,编译就正常了~~
  说实话,我不怎么会在命令提示符下编译程序,看了楼上的用法,我测试了一下刚刚下的版本 ,结果是3。4。2的~汗~~不知道楼上的哥们在哪里弄到的那个版本~~
  偶决定去查查gcc的资料~~可能在命令提示符下编译程序更灵活些~~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2026-1-23 19:56

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表