首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手,请问一个参数初始化有关问题

2012-04-05 
新手,请教一个参数初始化问题#includeiostream#include vectorusing namespace stdclass Student{pub

新手,请教一个参数初始化问题
#include <iostream>
#include <vector>
using namespace std;


class Student{
public:
  Student(const string& strName):m_strName(strName){}
  friend ostream& operator<<(ostream& os,const Student& student){
  return os<<'<'<<student.m_strName<<'>';
  }

private:
  string m_strName;
};

template<class T>
void print(T& vn){
  cout<<"向量元素数:"<<vn.size()<<endl;
  for(int i=0;i<vn.size();i++)
  cout<<vn[i]<<' ';
  cout<<endl;
}



int main(){
  vector<int> vn;
  vn.push_back(19);
  vn.push_back(99);
  print(vn);
  vector<int>::iterator it=vn.begin();
  *it=68;
  *(it+1)=89;
  print(vn);
  vn[0]=0;
  vn[1]=1;
  print(vn);
  vn[789]=576;
  print(vn);
  cout<<vn[789]<<endl;
  vn.pop_back();
  print(vn);
  vector<int>vn2(10,257);
  print(vn2);
  vector<Student>vn3(10,Student ("二"));
  print(vn3);
   
   
}


在这里面, vector<Student>vn3(10,Student ("二"));为什么可以直接把"二"初始化Student这个类,记得如果要初始化的话,不是要先new一个对象出来,在传入实参进去,才可以初始化的吗? 例如:Student abc("二").
  请大家指点一下,谢谢!


[解决办法]
1. 这个地方不能new的,因为模板参数是Student,而不是Student*
2. Student ("二")得到的就是一个Student对象
[解决办法]
这样的变量定义是合法的。而且因为你定义的构造函数Student(const string& strName):m_strName(strName){},至于为什么不用new,这个只是变量定义后存放位置的不同。
[解决办法]
Student ("二")得到一个临时Student对象.

热点排行