如何使两个字符串数组动态 [英] How to make an array of two strings dynamically
问题描述
我有一个问题,我应该在一个阵列使用了code这两个字符串,我不知道如何做到这一点。
这是我的code:
i have a problem,i should use this two strings in the code in an array,i dont know how to do it. This is my code:
#include <iostream>
#include <string>
#include <stdlib>
using namespace std;
class Employee
{
private:
string name;
string surname;
int ID;
float rate;
public:
Employee()
{
name=" ";
surname=" ";
ID=0;
rate=0;
}
Employee(string n,string sur,int i,float r)
{
name=n;
surname=sur;
ID=i;
rate=r;
}
string getName()const{return name;}
string getSurname()const{return surname;}
float getRate()const{return rate;}
int getID()const{return ID;}
void setRate(string r){rate=r;}
~Employee();
};
我的问题是把字符串名称和字符串姓阵列中的* EMP_NAME,并使用它像that.I知道如何使用析构函数,但我不能做的阵列。
My problem is to put string name and string surname in an array *emp_name,and use it like that.I know how to use the destructor ,but i cant do the array.
非常感谢!
推荐答案
这可能是他们想看到什么:
This is probably what they want to see:
class Employee {
public:
Employee()
{
emp_name = new string[2];
// just add your values to index 0 and 1
}
~Employee(); // delete[] the emp_name
private:
std::string* emp_name;
};
现在在析构函数,你将不得不删除分配的数组。你将不得不写一个拷贝构造函数(应该对象被复制,我们需要移动的资源)。和移动分配/构造函数(如果你使用的是C ++ 11)。
Now in the destructor you will have to delete the allocated array. And you will have to write a copy constructor (should the object be copied we need to move the resource). And move assign/constructor (if you are using C++11).
或者我们避免所有的麻烦,并使用一个向量:
Or we avoid all the trouble and use a vector:
#include <vector>
class Employee {
public:
Employee(string n, string sur, int i, float r)
: emp_name({ n, sur }),
ID(i),
rate(r)
{}
private:
vector<string> emp_name;
};
这篇关于如何使两个字符串数组动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!