返回信息流#include <iostream>
using namespace std;
class ABC
{
public:
int a;
void print(){ cout << a << endl; }
void print() const {cout << "wo yun" << endl;}
};
int main()
{
ABC d;
d.print();
return 1;
}
d.print()运行的时第一个函数。
那为什么这样定义不会出错呢?
如果要运行const的那个print函数,要怎么写呢‘?
这是一条镜像帖。来源:北邮人论坛 / soft-design / #22280同步于 2007/11/15
该镜像源已超过 30 天没有更新,可能在源站已被删除。
SoftDesign机器人发帖
C++中为什么这样定义也可以呢?
hman
2007/11/15镜像同步9 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
const和volatile在修饰成员函数,都可以重载.
#include <stdio.h>
#include <iostream>
using namespace std;
class test
{
public:
void print(){cout<<"p..."<<endl;}
void print() const{cout<<"p const..."<<endl;}
void print() volatile{cout<<"p volatile..."<<endl;}
};
int main()
{
test *T1=new test;
const test *T2=new test;
volatile test *T3=new test;
T1->print();
T2->print();
T3->print();
return 0;
}
【 在 hman 的大作中提到: 】
: #include <iostream>
: using namespace std;
: class ABC
: ...................
1楼正解,const成员函数可以用非const版本重载,选择使用哪一个重载成员函数由编译程序根据对象是否是const来决定。
我又看了一下书中关于function overload的概念 ,有几句话我写在下面。
Thus, for overloading to work the compiler must decorate the function name with the names of the argument types.
The compiler decorate the name, the scope, and the argument lists to produce internal names for it and the linker to use.
我看了这两句之后觉得函数重载的时候主要是看函数名和参数列表,但是实际运行的情况是把const,volatile这两个修饰也考虑进去了。
那请问在这种情况下 编译器是怎么做的呢?
【 在 hman 的大作中提到: 】
: 我又看了一下书中关于function overload的概念 ,有几句话我写在下面。
: Thus, for overloading to work the compiler must decorate the function name with the names of the argument types.
: The compiler decorate the name, the scope, and the argument lists to produce internal names for it and the linker to use.
: ...................
sign,中文一般翻译为函数签名
C++会把函数所在域(类)、原函数名、函数修饰符(就是你例子中的const)、参数类型都放到签名中,所以可以通过不同的修饰符、不同的参数来重载函数
由于签名中没有返回类型,所以返回类型不能作为重载的依据
我继续问一下哈。
#include <iostream>
using namespace std;
class ABC
{
public:
ABC(){a = 0;}
int a;
void print() { cout << "member" << endl; }
void print() const { cout << "const" << endl; }
static time() {cout << "time" << endl;}
};
int main()
{
ABC d;
const ABC e;
d.print();
e.print();
return 1;
}
现在在ABC类里就有两个print函数,而且这两个函数的函数签名是不一样的了。否则无法重载。
那现在我的问题来了。
对于对象d,这是一个普通对象(不是常对象),那这个对象“可以”调用两个print函数的任意一个。在上面的例子中,d.print()调用的是第一个print()函数。但是当我把第一个print注释掉,也就是ABC长成这个样子的时候:
class ABC
{
public:
ABC(){a = 0;}
int a;
//void print() { cout << "member" << endl; }
void print() const { cout << "const" << endl; }
static time() {cout << "time" << endl;}
};
上面的代码也是可以编译通过且运行正常的。但这个时候,我们发现d.print()调用的是那个常成员。现在的结论是这样的。
同样的一个调用方式:
d.print()
在不同的情况下可以link到具有不同函数签名的两个函数。
那这个是怎么做到的呢?
呵呵 , 不知道我有没有把问题说清楚哈。