关于c++类中的指针类型问题。。

2025-04-14 20:31:26
推荐回答(3个)
回答1:

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

using namespace std;

class Employee{

public:

//定义的构造函数

Employee(int *p){

num=p;

cout<<"sdf";

id="2";

};

//复制构造函数

Employee(string &employeename,int *p):name(employeename),id("2"),num(p){

};

//复制构造函数

Employee &operator=(Employee &rhs){

name = rhs.name;

id = rhs.id;

num = rhs.num;

cout << "in the operator constructor " << endl;

return *this;

}

//析构函数

~Employee() {

cout << "num is released ! " << endl;

//delete num;

}

private:

int *num;

string name;

string id;

};

int main(){

int number =12;

string s("string1");

Employee e1(s,&number);

}

//这样就可以了 如有疑问,可以追问

回答2:

第一个参数的类型,string&,这是引用临时对象的。
要允许引用临时对象,使用 const string&

回答3:

有问题,你在析构函数中delete num;但是你传number是在栈空间上的,肯定会有问题