c++,关于构造和析构函数,帮忙看看
#include<iostream>
using namespace std;
class MyA
{
public:
MyA(int i=5)
{
a=i;
cout<<"Constructor a="<<a<<endl;
}
MyA(MyA&P);
void setA(int i)
{a=i;}
int getA()
{return a;}
~MyA()
{
cout<<"Destructor a="<<a<<endl;
}
private:
int a;
};
MyA fun(MyA&);
void main()
{
MyA m1,m2(8);
cout<<"m1.a="<<m1.getA()<<endl;
cout<<"m2.a="<<m2.getA()<<endl;
m2=fun(m1);
cout<<"m1.a"<<m1.getA()<<endl;
cout<<"m2.a"<<m2.getA()<<endl;
}
MyA fun(MyA&Q)
{
Q.setA(88);
cout<<"Q.a="<<Q.getA()<<endl;
return Q;
}
编译时没有错误,但组建时提示有错误,怎么回事
[解决办法]
把
void setA(int i)
{a=i;}
int getA()
{return a;}中的a改为this.a试试
[解决办法]
MyA(MyA&P);
没定义
[解决办法]
- C/C++ code
#include "stdafx.h"#include<iostream>using namespace std;class MyA{public: MyA(int i=5) { a=i; cout<<"Constructor a="<<a<<endl; } MyA(MyA&P) { a = P.a; } void setA(int i) { a=i; } int getA() { return a; } ~MyA() { cout<<"Destructor a="<<a<<endl; }private: int a;};MyA fun(MyA&);void main(){ MyA m1,m2(8); cout<<"m1.a="<<m1.getA()<<endl; cout<<"m2.a="<<m2.getA()<<endl; m2=fun(m1); cout<<"m1.a"<<m1.getA()<<endl; cout<<"m2.a"<<m2.getA()<<endl;}MyA fun(MyA& Q){ Q.setA(88); cout<<"Q.a="<<Q.getA()<<endl; return Q;}