class中常数的封装问题

symansoft 2000-08-07 04:27:00


一般class封装的成员只能是变量,对于class中的常量如何封装呢?比如:人类 class Human,有2只手(即const int hands=2)而不可能为别的数,但如何将const int hands=2做为Human的成员封装呢。请C++高手指教,谢谢!
...全文
207 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Maxwell 2000-08-11
  • 打赏
  • 举报
回复
class c
{
int i, j;
const int k;
c(int, int);
....
}

c::c(int a, int b):i(a), j(b), k(10)
{
...
}
:后面是一个初始化表,类的变量可以在这里初始化,常量则必须用这种方法,变量还可在函数体内赋初值.
如果父类的构造函数需要参数,也用这种方法传递,还有类中的类成员的构造函数的参数传递.
xubin_sh 2000-08-10
  • 打赏
  • 举报
回复
: 初始化成员变量或以给定的参数初始化基类,const型的成员变量只能用此方法初始化
见MSDN/Visual Studio 6.0 Documentation/Visual C++ Documentation/Reference/C/C++ Languages and C++ Libraries/C++ Language Reference
symansoft 2000-08-10
  • 打赏
  • 举报
回复

诸位好!
近来上网不太通畅,故耽误了些时日。以上所言极是,但 Rubin_sh所举例子的构造函数的写法(函数名后只用一个冒号)以前没见过,能否解释一下。
本问题经过是这样的,我想设计一Chess类,其中初始局势(棋子及位置)是固定的,也就是常数,用一常数数组表示,显然应封装在Chess类中。但用以上各位说的方法仍然不行,望继续指教为谢!
haitian99 2000-08-08
  • 打赏
  • 举报
回复
Class CHuman
{
public:

const static int hand;
}

int CHuman::hand=2;
xubin_sh 2000-08-08
  • 打赏
  • 举报
回复
to qiaoxh:其实,class中的const在class construct时是可以设置其值的
to haitian99:你的例子是错误的 int CHuman::hand=2 有编译错误:CHuman::hand不是静态成员变量
给个小例子吧
#include "iostream.h"
class CHuman
{
public:
const int hand;
CHuman(int int_value):hand(int_value){;}
};
int main(int argc, char* argv[])
{
CHuman normal_man(2);//ok
CHuman yang_guo(1);//ok
cout << normal_man.hand << endl;
cout << yang_guo.hand << endl;
/*
normal_man.hand = 5;//error,because hand is const
*/
return 0;
}
qianxh 2000-08-08
  • 打赏
  • 举报
回复
杨过属于后天有一只手,其它先天就只有一只或三只的情况相信也不会没有。何苦要较真?
不过本人提供一法,可达到你的目的:
class CHuman
{
private:
int Fhands;
public:
__property int hands={read=Fhands};
};

CHuman::CHuman()
{
Fhands=2;
}


huntout 2000-08-07
  • 打赏
  • 举报
回复
class Human
{
public:
enum { hands = 2 };
}

you can call it as below:

int n = Human::hands;

13,822

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧