想要使C++控制台应用程序暂停,呈现命令行窗口的办法有如下几种:
一、针对Microsoft
#include <stdlib.h>
(1)第一种方式
system( "PAUSE ");
--------------------
(2)第二种方式
getchar(); // 这招对QT程序也有用
---------------------
(3)第三种方式
Sleep();
(1)第一种方式
system( "PAUSE ");
--------------------
(2)第二种方式
getchar(); // 这招对QT程序也有用
---------------------
(3)第三种方式
Sleep();
二、针对Linux
(1)第一种方式
getchar();
But,如何使程序在return 0之后暂停下来呢?终极解决方法是:
下面举个栗子!
StringX.h文件:
#pragma once
#include <stdio.h>
#include <stdio.h>
class StringX
{
public:
StringX(const char *str = NULL); //普通构造函数
StringX(const StringX &other); //复制构造函数
~StringX(void); //析构函数
StringX & operator=(const StringX &other); //赋值函数
private:
char *m_StringX; //私有成员,保存字符串
};
{
public:
StringX(const char *str = NULL); //普通构造函数
StringX(const StringX &other); //复制构造函数
~StringX(void); //析构函数
StringX & operator=(const StringX &other); //赋值函数
private:
char *m_StringX; //私有成员,保存字符串
};
#include "StringX.h"
#include <iostream>
#include <stdlib.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
StringX::~StringX(void)
{
cout<<"析构函数"<<endl;
if (m_StringX!=NULL)
{
delete [] m_StringX;
m_StringX=NULL;
}
}
{
cout<<"析构函数"<<endl;
if (m_StringX!=NULL)
{
delete [] m_StringX;
m_StringX=NULL;
}
}
StringX::StringX(const char *str)
{
cout<<"构造函数"<<endl;
if(str==NULL) //如果str为NULL,存空字符串""
{
m_StringX=new char[1]; //分配一个字节
*m_StringX='\0'; //将之赋值为字符串结束符
}
else
{
m_StringX=new char[strlen(str)+1]; //分配空间容纳str内容
strcpy(m_StringX,str); //复制str到私有成员
}
}
{
cout<<"构造函数"<<endl;
if(str==NULL) //如果str为NULL,存空字符串""
{
m_StringX=new char[1]; //分配一个字节
*m_StringX='\0'; //将之赋值为字符串结束符
}
else
{
m_StringX=new char[strlen(str)+1]; //分配空间容纳str内容
strcpy(m_StringX,str); //复制str到私有成员
}
}
StringX::StringX(const StringX &other)
{
cout<<"复制构造函数"<<endl;
m_StringX=new char[strlen(other.m_StringX)+1]; //分配空间容纳str内容
strcpy(m_StringX,other.m_StringX); //复制str到私有成员
}
{
cout<<"复制构造函数"<<endl;
m_StringX=new char[strlen(other.m_StringX)+1]; //分配空间容纳str内容
strcpy(m_StringX,other.m_StringX); //复制str到私有成员
}
StringX & StringX::operator=(const StringX &other)
{
cout<<"赋值函数"<<endl;
if (this==&other) //如果对象与other是同一个对象
{
return *this; //直接返回本身
}
delete [] m_StringX; //释放堆内存
m_StringX=new char[strlen(other.m_StringX)+1];
strcpy(m_StringX,other.m_StringX);
{
cout<<"赋值函数"<<endl;
if (this==&other) //如果对象与other是同一个对象
{
return *this; //直接返回本身
}
delete [] m_StringX; //释放堆内存
m_StringX=new char[strlen(other.m_StringX)+1];
strcpy(m_StringX,other.m_StringX);
return *this;
}
}
int fn(void)
{
system("PAUSE");
return 0;
}
{
system("PAUSE");
return 0;
}
int main()
{
_onexit(fn); //用_onexit注册回调函数,该函数可以在main函数结束之后调用
{
_onexit(fn); //用_onexit注册回调函数,该函数可以在main函数结束之后调用
StringX a("Hello"); //调用普通构造函数
StringX b("World"); //调用普通构造函数
StringX c(a); //调用复制构造函数
c=b; //调用赋值函数
StringX b("World"); //调用普通构造函数
StringX c(a); //调用复制构造函数
c=b; //调用赋值函数
return 0;
}
}