两个不明白的地方 谢谢指教

yang_e_2009 2009-05-30 10:10:49
学C++两个不明白的地方 谢谢指教
1. 书上说"只有一个形参且为类本身引用的构造函数是复制构造函数"
复制初始化 std::string s = "hello"; "hello" 不是C风格字符串吗? 不是string& 这是怎么回事呢? 谢谢回答

2.
char* abc()
{
char s[] = "hello";
return s;
} 可以这样返回一个在函数中创建的数组吗? s在函数结束后好像应该撤销 那返回的指针还有效果吗?
如果不行应该怎么做? 谢谢回答

谢谢
...全文
87 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
中才德创 2009-05-30
  • 打赏
  • 举报
回复
1:
std::string s = "hello";
// 是调用了string带参数(字符串)的那个构造函数,即__CLR_OR_THIS_CALL basic_string(const _Elem *_Ptr).

std::string temp = "hello";
std::string s = temp;
// 这才是复制(拷贝)构造函数
中才德创 2009-05-30
  • 打赏
  • 举报
回复
2:
const char * abc(void)
{
char *s="hello";
return s;
}
// 加const,是因为hello是不允许变更的.
// 加void,只是建议
Vegertar 2009-05-30
  • 打赏
  • 举报
回复
1: 你看的书说的不大准确。标准中对 copy constructor 定义是
A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&,
volatile X& or const volatile X&, and either there are no other parameters or else all other
parameters have default arguments [Example: X::X(const X&) and X::X(X&, int=1) are copy constructors.........

string可接受const char[] 因为函数是可以重载的。

2: 不能这样返回。可以这样 char* abc() { return "hello";// 常量字符串 }
effective_person 2009-05-30
  • 打赏
  • 举报
回复
1) 没有C风格这一说法

2) 返回局部变量是肯定要不得的,可以这样写
char * abc()
{
static char s[]="hello";
return s;
}
yang_e_2009 2009-05-30
  • 打赏
  • 举报
回复
谢谢大家了

65,211

社区成员

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

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