新人咨询关于new和关于指针的问题
请问使用vector和使用数组有什么区别?像我这样在代码中使用vector有什么不妥?
名称应该使用char* 还是使用 string?
为什么我用 vector<CTown> towns(10);会报错?vector<CTown> towns;这样就没有问题
我新建CTown要不要使用new?用和不用有什么区别呢?使用new就必需要使用*指针吗?
能不能使用 "第%d座城市名称是:%s" 这样进行格式化字符串?
个人是新手,对C++有无限的疑问,请大家帮助我解答。
----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------
执行结果如下

名称应该使用char* 还是使用 string?
为什么我用 vector<CTown> towns(10);会报错?vector<CTown> towns;这样就没有问题
我新建CTown要不要使用new?用和不用有什么区别呢?使用new就必需要使用*指针吗?
能不能使用 "第%d座城市名称是:%s" 这样进行格式化字符串?
个人是新手,对C++有无限的疑问,请大家帮助我解答。
----------------------------------------------------------------------------------------------------------
#include<string>
#include<iostream>
#include<vector>
using namespace std;
//将领
class CGeneral {
private:
string name;
public:
CGeneral( string name ){
this->name = name;
}
string getName() {
return this->name;
}
};
//城池
class CTown {
public:
CTown( string name ){
this->name = name;
}
string getName(){
return this->name;
}
int getGeneralCount() {
return this->generals.size();
}
bool append_general( CGeneral general ) {
this->generals.push_back( general );
return true;
}
private:
string name;
//城池中居住的将领
vector<CGeneral> generals;
};
//场景
class CScene {
private:
//场景中的城池
vector<CTown> towns;
public:
bool append_town( CTown town ){
this->towns.push_back( town );
return true;
}
int count_town() {
return this->towns.size();
}
CTown at(int index) {
return this->towns.at(index);
}
};
//创建场景
int main() {
CGeneral m_guanyu = CGeneral("关羽");
CScene scene;
CTown *town_xinye = new CTown("新野");
town_xinye->append_general( m_guanyu );
scene.append_town( *town_xinye );
CTown town_xuchang = CTown("许昌");
scene.append_town( town_xuchang );
CTown town_jianye = CTown("建业");
scene.append_town( town_jianye );
cout<<"场景中目前有城池数:"<<scene.count_town()<<"\n"<<endl;
string msg;
for(int i=0; i<scene.count_town();i++) {
CTown t = scene.at(i);
cout<<"第"<<i+1<<"城池名称是:"<<t.getName()<<"\t"<<"居住的将领人数:"<<t.getGeneralCount()<<endl;
}
return 0;
}
-----------------------------------------------------------------------------
执行结果如下

...全文
相关推荐
Java回调函数的理解
- **服务程序**(S):朋友扮演服务程序的角色,负责思考解决问题的方法并最终告知解决方案。- **函数A**:相当于“我”向朋友咨询问题的行为。
【C/C++ 面试必备 | 基础概念】C++ new和malloc的区别
这里先对new和delete简单进行一下总结,然后再细说new和malloc的区别。一、new和deleteC语言提供了malloc和free两个系统函数,完成对堆内存的申请和释放。而C++则提供了两个关键字new和delete;1.1 规则new/delete是关键字,效率高于malloc和free。配对使用,避免内存泄漏和多重释放。避免交叉使用,比如malloc申请空间delete释放...
NEW 《能力素质模型咨询工具》胜任力数据库.doc
"《能力素质模型咨询工具》是大型咨询公司资深咨询顾问设计的一个全面评估和培养员工能力的工具。该文档包含了一份胜任力数据库,包括了远见卓识、系统思考和制订决策三个关键能力领域的行为表现描述,用于帮助企
专题四 - 指针和数组(上)
根据提供的信息,我们可以深入探讨关于指针和数组的基础知识,特别是针对Java编程语言中的应用。虽然提供的部分内容更多地涉及了C语言的概念,但基于题目要求,我们主要关注于Java环境中这些概念的应用。
咨询顾问
在IT行业中,"咨询顾问"的角色至关重要,他们通常负责帮助企业解决技术问题,规划信息系统,以及优化业务流程。


