拷贝构造函数

fight_flight 2010-01-27 10:06:31
#include<iostream>
#include<string>
using namespace std;
class A{
private:
int a;
string s;
public:
A(){
a=0;
s="";
}
A(int a,string& s){
this->a=a;
this->s=s;
}
A(const A& p){
a=p.a;
s=p.s;
//a=p.geta();外什么用这两句替换上面两句会编译出错
//s=p.gets();
}
int geta(){return a;}
string gets(){return s;}
};
int main(){
return 0;
}
...全文
110 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
hacker1125 2010-01-27
  • 打赏
  • 举报
回复
const对象只能访问const成员函数,而非const对象可以访问任意的成员函数,包括const成员函数.
ithiker 2010-01-27
  • 打赏
  • 举报
回复
楼上正解,看c++ primer时这块讲的不太清楚,java中倒是很明白
pengzhixi 2010-01-27
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 wocaoqwer 的回复:]
错误提示为:error C2662: 'geta' : cannot convert 'this' pointer from 'const class A' to 'class A &'
另外加上const就可以了,为什么呢
[/Quote]
因为你的拷贝构造函数里面的参数p是const&所以他只能调用const修饰的函数。
fight_flight 2010-01-27
  • 打赏
  • 举报
回复
知道了
fight_flight 2010-01-27
  • 打赏
  • 举报
回复
错误提示为:error C2662: 'geta' : cannot convert 'this' pointer from 'const class A' to 'class A &'
另外加上const就可以了,为什么呢
allahser 2010-01-27
  • 打赏
  • 举报
回复
const对象只能访问const成员函数,而非const对象可以访问任意的成员函数,包括const成员函数.
受教了.
三文鱼也会飞 2010-01-27
  • 打赏
  • 举报
回复
int geta() const {return a;}
string gets() const {return s;}
traceless 2010-01-27
  • 打赏
  • 举报
回复
如果用const修饰的类指针或引用变量,调用的方法要用const来修饰函数尾部
老吴笔记 2010-01-27
  • 打赏
  • 举报
回复
这样喽:

#include <iostream>
#include <string>
using namespace std;
class A
{
private:
int a;
string s;
public:
A()
{
a=0;
s="";
}
A(int a,string& s)
{
this->a=a;
this->s=s;
}
A(const A& p)
{
//a=p.a;
//s=p.s;
a=p.geta(); //外什么用这两句替换上面两句会编译出错
s=p.gets();
}
int geta() const
{
return a;
}
string gets() const
{
return s;
}
};
int main()
{
return 0;
}
pengzhixi 2010-01-27
  • 打赏
  • 举报
回复
int geta()const{return a;}
string gets()const{return s;}
这样就没问题
allahser 2010-01-27
  • 打赏
  • 举报
回复
2L有道理,建议LZ在MAIN函数中写全了再试试
boksic 2010-01-27
  • 打赏
  • 举报
回复
错误提示发一下
allahser 2010-01-27
  • 打赏
  • 举报
回复
mark,等高人解答.
zhou1xp 2010-01-27
  • 打赏
  • 举报
回复
现在你的构造函数都还没执行,那里有this指针去调用成员函数
冻结 2010-01-27
  • 打赏
  • 举报
回复
int geta() const
{return a;}
string gets()const
{return s;}

试一试。

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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