const成员函数的定义和使用
#include <iostream>
using namespace std;
class CSample
{
int a,b;
public:
CSample(int x,int y)
{
a=x;
b=y;
cout < < "调用类CSample的构造函数 " < <endl;
}
~CSample()
{
cout < < "调用类CSample的析构函数 " < <endl;
}
void PrintAB();
void PrintAB() const;
const void Test()
{
}
}
void CSample::PrintAB()
{
cout < < "调用函数CSample::Print AB()! " < <endl;
cout < < "A= " < <a < < '\t ' < < "B= " < <b < <endl;
}
void CSample::PrintAB() const
{
cout < < "调用函数CSAmple:;PrintAB() " < <endl;
cout < < "A= " < <a < < '\t ' < < "B= " < <b < <endl;
}
int main()
{
CSample s1(11,22);
CSample const s2(33,44);
s1.PrintAB();
s2.PrintAB();
system( "PAUSE ");
return 0;
}
各位想问下这个程序究竟是什么问题啊?
无法运行的 这是我们教材上的一个习题
我看了一下出错提示是说函数无法重载
可是
void PrintAB();
void PrintAB() const;
这两个函数应该是属于不同的 那么为什么会无法重载呢?
[解决办法]
void PrintAB();
void PrintAB() const;
可以重载函数
[解决办法]
class CSample
{
int a,b;
public:
CSample(int x,int y)
{
a=x;
b=y;
cout < < "调用类CSample的构造函数 " < <endl;
}
~CSample()
{
cout < < "调用类CSample的析构函数 " < <endl;
}
void PrintAB();
void PrintAB() const;
const void Test()
{
}
}
===
加分号
[解决办法]
class ***
{
//...
};
即可以
okokok
[解决办法]
应该可以运行,
你用什么编译器?
专门在vs2005测了一下,可以运行
输出结果:
-----------------
调用类CSample的构造函数
调用类CSample的构造函数
调用函数CSample::Print AB()!
A=11 B=22
调用函数CSAmple:;PrintAB()
A=33 B=44
Press any key to continue . . .
------------------
const 对象只能调用const方法,
非const 对象const 和 非 const 都可以调用。
类中可以用const 关键字重载函数,
但是标准c++上 "好像 "说只能根据函数签名(函数名字, 参数类型, 参数数量,顺序)来重载函数.
并没有说是可以根据const 关键字
是不是 "vs2005 " 自己没有按照标准做?