还是讨论继承中的拷贝构造函数
请教一下各位朋友,把对象按引用传递,也会调用拷贝构造函数吗?下面是一个例子,问题用注释标了出来,请大家指点一下.谢谢!
//tabtenn.h--包含了基类和派生类的声明
#ifndef TABTENN_H_
#define TABTENN_H_
#include <iostream>
using namespace std;
class TableTennisPlayer
{
private:
enum{LIM=20};
char firstName[LIM];
char lastName[LIM];
bool hasTable;
public:
TableTennisPlayer(const char *fn="noName",
const char *ln="noName",
bool ht=false);
/*
TableTennisPlayer(TableTennisPlayer &ttp)
{
cout << "TableTennisPlayer copy constructor called!\n";
}
*/ // 添加自定义的拷贝构造函数,则编译出错!这是为什么?
TableTennisPlayer(TableTennisPlayer &ttp);
void ShowName()const;
bool HasTable()const
{
return hasTable;
}
void ResetTable(bool v)
{
hasTable=v;
}
};
class RatedPlayer:public TableTennisPlayer
{
private:
unsigned int rating;
public:
RatedPlayer(unsigned int r=0, const char *fn="noName",
const char *ln="noName", bool ht=false);
RatedPlayer(unsigned int r, const TableTennisPlayer &tp);
unsigned int Rating()
{
return rating;
}
void ResetRating(unsigned int r)
{
rating=r;
}
};
#endif
//tabtenn.cpp--基类与派生类成员函数的实现
#include "tabtenn.h"
#include <iostream>
#include <cstring>
using namespace std;
TableTennisPlayer::TableTennisPlayer(const char *fn,const char *ln, bool ht)
{
strncpy(firstName, fn, LIM-1);
firstName[LIM-1]='\0';
strncpy(lastName, ln, LIM-1);
lastName[LIM-1]='\0';
hasTable=ht;
}
void TableTennisPlayer::ShowName()const
{
cout << lastName << "," << firstName << endl;
}
RatedPlayer::RatedPlayer(unsigned int r,const TableTennisPlayer &tp):TableTennisPlayer(tp),
rating(r)
//这里的对象是按引用传递,并不是按值传递,那为什么还会调用拷贝构造函数?{
}
RatedPlayer::RatedPlayer(unsigned int r, const char *fn, const char *ln, bool ht):TableTennisPlayer(fn,ln,ht)
{
rating=r;
}
//usetabtenn.cpp -- 主函数,,使用上述代码.
#include "tabtenn.h"
#include <iostream>
using namespace std;
int main(void)
{
TableTennisPlayer player_1("Tara", "Boomdea", false);
RatedPlayer rplayer_1(1104, "Mallory", "Duck", true);
rplayer_1.ShowName();
if(rplayer_1.HasTable())
cout << "has a table.\n";
else cout << "don't have a table.\n";
player_1.ShowName();
if(player_1.HasTable())
cout << "has a table.\n";
else cout << "don't have a table.\n";
rplayer_1.ShowName();
cout << " 's rating : " << rplayer_1.Rating() << endl;
RatedPlayer rplayer_2(1212, player_1);
cout << "Name:";
rplayer_2.ShowName();
cout << " 's rating : " << rplayer_2.Rating() << endl;
return 0;
}