记一道C++题
上学的时候就没好好学C++,之前有个学弟求助,帮忙做了一道题,运算符重载,友元函数什么的都忘了,得会有万能的百度
题目如下
代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
class MyString
{
public:
MyString(int n)
{
c = (char*)malloc(sizeof(char)*n);
}
char& operator[](int index);
friend ostream& operator<< (ostream& out, const MyString& s);
private:
char* c;
};
//重载数组下标运算符[]
char& MyString::operator[](int index)
{
return c[index];
}
//重载输出运算符
//用成员方式重载运算符,不能改变参数的个数,二元运算符用成员重载时,
//只需要一个参数,另一个参数由this指针传入.如果需要两个参数,
//那么可以在类外面定义,然后在类里声明为友元
ostream& operator<<(ostream& out, const MyString& s)
{
out << s.c;
return out;
}
int main()
{
MyString str(10);
char* S = "Welcome!";
for(int i=0;i<10;i++)
str[i] = S[i];
cout<<str<<endl;
return 0;
}