C++的引用问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 14:49:38
// proj1.cpp
#include <iostream>
using namespace std;

class MyClass {
char * p;
public:
MyClass(char c) { p = new char; *p = c; }
// 为什么下面这段代码copy前必须加上 &,删除就编译有误呢
MyClass(const MyClass ©) { p = new char; *p = *(copy.p); }
~MyClass() {delete p; }
MyClass& operator=(const MyClass & rhs)
{
if ( this == &rhs ) return *this;
*p = *(rhs.p);
return *this;
}
char GetChar() const { return *p; }
};
int main()
{
MyClass obj1('C'), obj2('P');
MyClass obj3(obj1);
obj3 = obj2;
cout << "The extension is: "
<< obj1.GetChar() << obj2.GetChar()
<< obj3.GetChar() << endl;
return 0;
}

#include <iostream>
using namespace std;

class MyClass
{
char *p; //定义一个字符型指针变量
public:
MyClass(char c) //构造函数
{
p = new char;
*p = c;
}
// 为什么下面这段代码copy前必须加上 &,删除就编译有误呢
MyClass(const MyClass & copy)//复制构造函数
{
p = new char;//
*p = *(copy.p);//将对象属性地址赋值给指针p
}
~MyClass()//析构函数
{
delete p;
}
MyClass& operator=(const MyClass &rhs) //对运算符=重载
{
if ( this == &rhs ) return *this;
*p = *(rhs.p);
return *this;
}
char GetChar() const { return *p; } //常成员函数GetChar
};

int main()
{
MyClass obj1('C'), obj2('P'); //用构造函数建立两个对象obj1属性是C,obj2属性是P
MyClass obj3(obj1); //用复制构造函数建立对象obj3,调用copy方法
obj3 = obj2; //将obj2的内容赋值给obj3/调用重载函数
cout << "The extension is: "
<< obj1.GetChar(