64,690
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class test{
public:
int *p;
test(int value){
p = new int(value);
}
~test(){
delete p;
p = NULL;
}
test(const test &other){
p = new int(*other.p);
}
test & operator = (const test &pt){
if( this == &pt ) return *this;
delete p;
p = new int(*pt.p);
return *this;
}
bool operator == (const test &other){
return p == other.p;
}
friend ostream & operator << ( ostream &os, test &A ){
os << *A.p;
return os;
}
void printvalue(){
cout<<"the value is "<<*p<<endl;
}
};
void func(test t){
cout<<"in the func value is "<< t <<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test t1 = 33;
func(t1);
t1.printvalue();
system("pause");
return 0;
}
bool operator == (const test &other){ return p == other.p; }
这个会出现==的情况吗?
void foo(int x){
}
int j;
foo(j); //实参j会被用来初始化x, 相当于int x = j;
所以你只需要明白“在对象/变量的定义(的同时初始化)”就够了。
std::string a = "hello"; //调用构造函数std::string(char const*)
std::string b = a; //copy, 调用了拷贝构造函数
std::string& c = a; //no copy,没有调用构造函数
//c++11 中还有move构造函数
using namespace std;
class test{
int *p;
public:
test(int value){
p = new int(value);
cout<<"Execute Constructor"<<endl;
cout<<"p的地址为"<<&p<<"前p的值为"<<p <<" *p的值为"<<*p<<endl;
}
~test(){
cout<<"Execute Destructor"<<endl;
delete p;
p = NULL;
}
test(const test &other){
cout<<"Execute Copy Constructor"<<endl;
p = new int(*other.p);
}
test & operator = (const test &pt){
cout<<"Test operator"<<endl;
cout<<"前p的地址为"<<&p<<"前p的值为"<<p <<" *p的值为"<<*p<<endl;
p = new int(*pt.p);
cout<<"前p的地址为"<<&p<<"后p的值为"<<p <<" *p的值为"<<*p<<endl;
return *this;
}
bool operator == (const test &other){
return p == other.p;
}
friend ostream & operator << ( ostream &os, test &A ){
os << *A.p;
return os;
}
void printvalue(){
cout<<"the value is "<<*p<<endl;
}
};
void func(test t){
cout<<"Waiting... "<<endl;
t.operator=(5);
cout<<"in the func value is "<< t <<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test t1 = 33;
func(t1);
t1.printvalue();
return 0;
}
int *p = new int(5);
int *p1 = p;
delete p;
cout<<*p1<<endl;//不会输出5
但你重新定义了复制构造函数后,相当于下面的代码:
int *p = new int(5);
int *p1 = new int(*p);
delete p;
cout<<*p1<<endl;//输出5