C++入门练习

///string和C的转化
#include 
#include 
#include 
using namespace std;


int main()
{
	char cstr[10] = "HELLO";
	string cppstr = "WORLD";
	string ccstr(cstr);//[C->C++]
	/*以后我记住了C++中不能用cout输出string,所以我尽量避免,若用到string类型输出,则先将string转为char**/
	//cout << cppstr <C %s]\r\n", cppstr.c_str());
	system("pause");
	return 0;
}

基础案例
#include 
using namespace std;
class girl
{
public:
	void sleep();
	void shop();
	girl();//构造函数不能有返回值 就直接裸写
private:
};

void girl::sleep()
{
	printf("%s\r\n",__FUNCTION__);
}
void girl::shop()
{
	printf("%s\r\n", __FUNCTION__);
}
girl::girl()
{
	printf("%s\r\n", __FUNCTION__);
}

int main()
{
	girl yougirl;
	yougirl.shop();
	///
	girl *p1girl = &yougirl;
	p1girl->sleep();
	///
	girl *p2girl = new girl;
	p2girl->sleep();
	p2girl->shop();

}


girl::girl
girl::shop
girl::sleep
girl::girl
girl::sleep
girl::shop



/构造函数2中办法处理重名 

#include 
using namespace std;
class girl
{
public:
	girl();
	girl(string name, int age);
	girl(int age, string name);
	void show()
	{
		cout << name.c_str() << age << endl;
	}
private:
	int age;
	string name;
};

girl::girl()
{
	printf("%s\r\n", __FUNCTION__);
}

//提供下面2中方法解决参数重名的问题1--初始化参数列表 2--this指针
girl::girl(string name,int age):name(name),age(age)
{
	printf("%s %d\r\n", __FUNCTION__,__LINE__);
}

girl::girl(int age,string name)
{
	printf("%s %d\r\n", __FUNCTION__, __LINE__);
	this->age = age;
	this->name = name;
}

int main()
{
	girl *p1girl = new girl;
	girl *p2girl = new girl("lisa", 18);
	girl *p3girl = new girl(28, "luna");
	p1girl->show();
	p2girl->show();
	p3girl->show();
}

girl::girl
girl::girl 26
girl::girl 31
-842150451
lisa18
luna28

 

你可能感兴趣的:(C++入门练习)