在复制构造函数中没法输出char数组
在复制构造函数中无法输出char数组
myclass.h
myclass.cpp
main.cpp
重载了[]运算符,输出指定索引的字符。但是为什么在复制构造函数中却无法输出呢?
------解决方案--------------------
我觉得是因为你的形参是const MyClass &temp,而const对象只能调用const成员函数。
------解决方案--------------------
char operator[](int idx)改成
char operator[](int idx)const
如果有需要,可以改成重载形式
char& operator[](int idx)//非const对象返回引用,可以直接修改内部数据
char operator[](int idx)const//const对象返回值
myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
char str[4];
public:
MyClass();
MyClass(const MyClass &temp);
~MyClass();
void Show();
char operator[](int idx);
};
#endif // MYCLASS_H
myclass.cpp
#include <iostream>
#include "myclass.h"
using std::cout;
using std::endl;
MyClass::MyClass()
{
str[0] = 'A';
str[1] = 'B';
str[2] = 'C';
str[3] = 'D';
cout << "Create" << endl;
}
MyClass::MyClass(const MyClass &temp)
{
cout << "Create2" << endl;
cout << temp[1] << endl; // 二进制“[”: 没有找到接受“const MyClass”类型的左操作数的运算符(或没有可接受的转换)
}
MyClass::~MyClass()
{
cout << "Destory" << endl;
}
void MyClass::Show()
{
cout << str << endl;
}
char MyClass::operator [](int idx)
{
return str[idx];
}
main.cpp
#include <iostream>
#include "myclass.h"
using namespace std;
int main()
{
MyClass o;
cout << o[1] << endl; // 这里却可以
system("pause");
return 0;
}
重载了[]运算符,输出指定索引的字符。但是为什么在复制构造函数中却无法输出呢?
------解决方案--------------------
我觉得是因为你的形参是const MyClass &temp,而const对象只能调用const成员函数。
------解决方案--------------------
char operator[](int idx)改成
char operator[](int idx)const
如果有需要,可以改成重载形式
char& operator[](int idx)//非const对象返回引用,可以直接修改内部数据
char operator[](int idx)const//const对象返回值