高手看看。遇到问题需要您的指教!

来源:百度知道 编辑:UC知道 时间:2024/05/11 00:33:20
#include <iostream>
#include <string.h>
using namespace std;

class String {
private:
char *ptr;
public:
String();
String(char *s);
~String();

int operator==(const String &other);
operator char*() {return ptr;}
};

void main() {
String a("STRING 1");
String b("STRING 2");
cout << "The value of a is: " << endl;
cout << a << endl;
cout << "The value of b is: " << endl;
cout << b << endl;
}

// ----------------------------------
// 函数定义

String::String() {
ptr = new char[1];
ptr[0] = '\0';
}

String::String(char *s) {
int n = strlen(s);
ptr = new char[n + 1];
strcpy(ptr, s);
}

String::~S

我ctrl+v过来,结果是:
The value of a is:
String 1
The value of b is:
String 2
不知道你为什么得不到正确结果。
另:(和本题无关)
建议你将main()定义为int 类型。
我这里用void main() {}不能通过编译。

因为你自己的类String不能被cout正确输出(默认的行为是输出类实例的地址),你需要重载<<运算符,然后就可以了,方法如下:
class String {
private:
char *ptr;
public:
String();
String(char *s);
~String();

int operator==(const String &other);
operator char*() {return ptr;}
friend ostream& operator<<(ostream& os, String& s){
os<<s.ptr;
return os;
}
};