自定义类内对std::string的引用问题

xiaolomg xiaolomg 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我自己定义了一个Test类:

#include<iostream>
#include <string>

using namespace std;

class Test
{
public:
Test(){}
Test(string &aStr):m_Str(aStr){}
const char& operator[](size_t aPos)const
{
return m_Str[aPos];
}
char& operator[](size_t aPos)
{
return m_Str[aPos];
}
private:
string m_Str;
};

int main()
{
Test t("test");//这里会出现error,const char*不能转化为string&
cout << t[0] << endl;
const Test lTest("Halen");
cout << lTest[1] << endl;
}

等我修改为
#include<iostream>
#include <string>

using namespace std;

class Test
{
public:
Test(){}
Test(string aStr):m_Str(aStr){}
const char& operator[](size_t aPos)const
{
return m_Str[aPos];
}
char& operator[](size_t aPos)
{
return m_Str[aPos];
}
private:
string m_Str;
};

int main()
{
Test t(string("test"));
cout << t[0] << endl;
const Test lTest("Halen");
cout << lTest[1] << endl;
}

就行了,这是为什么呢?求解答
...全文
评论 6
收藏 已收藏
分享
返回顶部
xiaolomg
C++ 语言 65,214 成员 250,514 内容