分享
 
 
 

C++Builder常用代码片断

王朝c/c++·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

Delete all Tables in Alias void TData

A:hover {color: #FF0000; font-style: italic; font-weight: bold}

C++Builder代码片断

本文中包含了一些常用的代码片断,看看想想或许有他山之石可以攻玉的可能。

CKER

删除别名中所有的表

纯虚函数

虚函数

启动页面

指针

为指针解除引用

表的For循环

变量与常量的声明

检查表是否存在

组件的类名

剪贴板中的文字

字符流

检查表是否已打开

表的状态操作

改变PageControl的标签

向Query传递参数

日期属性

绘制状态条

删除别名中所有的表

void TData::CleanTemp()

{

TStringList *myTables = new TStringList();

TTable *Table = new TTable(this);

try

{

Session-GetTableNames("Temp", "", True, False, myTables);

}

catch (...) {}

// AnsiString str = myTables->GetText();

// ShowMessage(str);

for(int count=0; count < myTables-Count; count++)

{

Table-DatabaseName = "Temp";

Table-TableName = myTables-Strings[count];

Table-Close();

Table-DeleteTable();

}

delete myTables;

delete Table;

}

BACK 纯虚函数

//纯虚函数只在基类中出现,而在子类中必须有

//与其匹配的成员函数。程序中申明的子类的实例

file://必须为基类中的每一个纯虚函数提供一个重载的成员函数。

class TBaseClass

{

public:

virtual void Display() = 0;

};

class TDerivedClass : public TBaseClass

{

public:

void Display() { ShowMessage("From Derived"); }

};

class TSecondDerivedClass : public TDerivedClass

{

public:

void Display() { ShowMessage("From Second Derived"); }

};

void __fastcall TForm1::Button1Click(TObject *Sender)

{

TDerivedClass dc; dc.Display();// "From Derived"

TSecondDerivedClass sc; TBaseClass* bc = &sc;

bc-Display(); // "From Second Derived"

}

BACK

虚函数

//虚函数作为其他类的父类的成员函数。

//如果继承子类成员函数中存在与父类成员函数完全相同的函数,

//子类中的成员函数永远有效。

class Base

{

public:

virtual void Display() { ShowMessage("Base Class"); }

};

class DerivedOne : public Base

{

public:

void Display() { ShowMessage("DerivedOne"); }

};

class DerivedTwo : public Base

{

public:

void Display() { ShowMessage("DerivedTwo"); }

};

Base* pBases[10];

int count = 0;

DerivedOne aDerOne;

DerivedTwo aDerTwo;

pBases[count++] = &aDerOne;

pBases[count++] = &aDerTwo;

for( int i=0; i < count; i++ )

pBases[i]-Display();

BACK

启动页面

USEDATAMODULE("Datamod.cpp", DataModule);

USEFORM("about.cpp", AboutBox);

USEFORM("main.cpp", MainForm);

USEFORM("splash.cpp", SplashForm);

file://---------------------------------------------------------------------------

#include "splash.h"

WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)

{

try

{

SplashForm = new TSplashForm(Application);

SplashForm-Show();

SplashForm-Update();

Application-Initialize();

Application-Title = "Example of Loading Splash Form";

Application-HelpFile = "SplashHelp.hlp";

Application-CreateForm(__classid(TMainForm), &MainForm);

Application-CreateForm(__classid(TDataModule), &DataModule);

Application-CreateForm(__classid(TAboutBox), &AboutBox);

SplashForm-Hide();

SplashForm-Close();

Application-Run();

}

catch (Exception &exception)

{

Application-ShowException(&exception);

}

return 0;

}

BACK

指针

int array[] = { 2, 4, 6, 8, 10}

int myInteger = array[3]; //

值为

8

// ----使用指针可以实现同样的功能

-----

int array[] = { 2, 4, 6, 8, 10}

int* myPtr = array;

int myInteger = myPtr[3]; //

值为8

BACK 为指针解除引用 int x = 32;

int* ptr = &x;

//解除指针的引用

file://以获得内存位置的内容

int y = *ptr; // y = 32

BACK

表的For循环

void TDataModuleEmployee::ListNames( TStrings *Items )

{

try

{

for ( TableAll-First(); !TableAll-Eof; TableAll-Next() )

if ( TableAll-FieldByName("Deleted")-AsBoolean == false )

Items-AddObject( TableAll-FieldByName("Name")-AsString, (TObject *)TableAll-FieldByName("Refnum")-AsInteger );

}

catch (Exception &e)

{

Application-ShowException(&e);

};

}

BACK

变量与常量的声明

char ch;

int count = 1;

char* name = "csdn.net";

struct complex { float my, his;};

float real(complex* p) {return p-my};

const double pi = 3.1415926535897932385;

templetate abc(T a) { return a < 0 ? -a : a; };

enum WebSite { one, two, three, four};

int* a; // * 指针

char* p[20]; // [ ] 数组

void myFunction(int); // ( )函数

struct str { short length; char* p; };

char ch1 = 'a';

char* p = &ch1; // &引用 ,p保持着ch1的地址

char ch2 = *p; // ch2 = 'a'

BACK

检查表是否存在

#include "io.h"

if (access(Table1-TableName.c_str(),0)) file://检查表是否存在

{ // 若不存在就创建 ...

Table1-Active = false;

Table1-TableType = ttParadox;

Table1-FieldDefs-Clear();

Table1-FieldDefs-Add("Myfield", ftString, 15, false);

Table1-IndexDefs-Clear();

Table1-CreateTable();

Table1-Active = true;

}

else

Table1-Active = true;

BACK

组件的类名

//找出丢失的组件类名

for(int i=0; i < ComponentCount; i++)

{

if(String(dynamic_cast<TComponent&(*Components[i]).Name) == "")

{

ShowMessage(Components[i]-ClassName());

}

}

BACK

剪贴板中的文字

#include "memory.h" // 包含 auto_ptr<

#include "clipbrd.hpp" file://包含 TClipboard & Clipboard()

// 范例程序,包含了一个memo控件

__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)

{ file://创建 TStringList对象

auto_ptr ClipText(new TStringList); file://得到剪贴板中的文字的拷贝

ClipText-Text = Clipboard()-AsText; file://然后加工一下...

Memo1-Lines-AddStrings(ClipText.get());

}

BACK

字符流

//范例一

#include "sstream"

const char *name = "cker";

const char *email = "cker@sina.com";

// 生成

"cker"[SMTP:cker@sina.com]

ostringstream ost;

ost << "\"" << name << "\"[SMTP:" << email << "]";

Edit1-Text = ost.str().c_str();

file://范例二

void TDataModuleEmployee::FullReport(const char *title)

{

Report.header(title);

Report << sformat( "Employee #%2d: %s%s\n", TableAllRefnum-Value, TableAllName-Text.c_str(),

TableAllManagerFlag-Value ?"(Manager)" : "" ) << " Address: " <<

TableAllAddress-Text.c_str() << endl << " " << TableAllCityProvZip-Text.c_str() <<

endl << " " << NameCountry(TableAllCanada-Value) << endl;

Report.footer();

}

BACK

检查表是否已打开

void TData::CheckEdit()

{

for(int i=0; i < ComponentCount; i++)

{

if(dynamic_cast(Components[i]))

{

if(((TTable*)Components[i])-State == dsEdit)

{

String s = "Table " + Components[i]-Name + " is in edit mode" "\rWould you like to post it before entering new task?";

if(MessageBox(NULL,s.c_str(),"Table in Edit Mode",MB_YESNO | MB_ICONINFORMATION) == IDYES)

((TTable*)Components[i])-Post(); else ((TTable*)Components[i])-Cancel();

}

}

}

}

BACK

表的状态操作

//关闭已打开的表并将他们恢复成初始状态。

void TData::MyTables(TForm * sender)

{

int i;

TTable * Table;

bool *active = new

bool[MyClass->ComponentCount];//在动态数组中存放每个表的初始状态,然后关闭所有的表

for(i = 0; i < MyClass-ComponentCount; i++)

{

try

{

if((Table = dynamic_cast(MyClass-Components[i])) != NULL)

{

active[i] = Table-Active;

Table-Active = false;

}

}

catch(...) {}; file://异常应该只来自于dynamic cast...

}

for(i = 0; i < MyClass-ComponentCount; i++)

{

try

{

if((Table = dynamic_cast(MyClass-Components[i])) != NULL)

{

if(Table-DatabaseName != OPTARDatabase-DatabaseName)

continue;

DBIResult result = DBIERR_NONE + 1;

while(result != DBIERR_NONE) file://若希望的话,这样允许用户重试!

{

result = DbiPackTable (OPTARDatabase-Handle,NULL,Table-TableName.c_str(),NULL, true);

if(result != DBIERR_NONE)

{

AnsiString rsltText = "Unable to pack " + Table-TableName + "." ;

char rslt[DBIMAXMSGLEN + 1];

DbiGetErrorString(result, rslt) rsltText += ". Try again?";

if(Application-MessageBox(rsltText.c_str(), "Error!",MB_YESNO) != IDYES)

break;

}

}

}

}

catch (...) {};

file://异常应该只来自于dynamic cast...

}

//

将所有的表设回初始状态。

for(i = 0; i < MyClass-ComponentCount; i++)

{

try

{

if((Table = dynamic_cast(MyClass-Components[i])) != NULL)

Table-Active = active[i];

}

catch(...) {};

}

delete []active;

}

BACK

改变PageControl的标签

void __fastcall TfmMainForm::Cancel1Click(TObject *Sender)

{

int i;

switch (PageControl1-ActivePage-Tag))

{

case 1:

for (i=0; i < ComponentCount; i++)

{

if (dynamic_cast(Components[i]))

dynamic_cast(Components[i])-Enabled = false;

}

Data-tbDetail-Cancel();

break;

case 2:

for (i=0; i < ComponentCount; i++)

{

if (dynamic_cast(Components[i]))

dynamic_cast(Components[i])-Enabled = false;

}

Data-tbDetail-Cancel();

break;

case 3:

for (i=0; i < ComponentCount; i++)

{

if (dynamic_cast(Components[i]))

dynamic_cast(Components[i])-Text = "";

}

break;

}

}

BACK

向Query传递参数

// 直接从表向Query传递参数的一种方法

TQuery *Query = new TQuery(this);

Query-DatabaseName = "dbServer";

Query-SQL-Clear();

Query-SQL-Add("DELETE FROM 'Events.DB' WHERE (TicketNo = " + Data-tbProblem-FieldByName("TicketNo")-AsString + ")" );

Query-ExecSQL();

Query-Close();

delete Query;

BACK

日期属性

TMaskEdit *meOpen;

TLabel *lbCount1;

TDateTime Date2;

void __fastcall TfmMainForm::CountOpen(TObject *Sender)

{

switch(dynamic_cast<TComponent&(*Sender).Tag)

{

case 1:

count1 = StrToInt(lbCount1-Caption);

count1 += 1;

Date2 = Now() + count1;

meOpen-Text = Date2.DateString();

lbCount1-Caption = IntToStr(count1);

break;

case 2:

count1 = StrToInt(lbCount1-Caption);

count1 -= 1;

Date2 = Now() + count1;

meOpen-Text = Date2.DateString();

lbCount1-Caption = IntToStr(count1);

break;

}

}

BACK

绘制状态条

void __fastcall TForm1::StatusBar1DrawPanel(TStatusBar *StatusBar, TStatusPanel *Panel, const TRect &Rect)

{

TCanvas& c = *StatusBar-Canvas;

switch (Panel-Index)

{

case 0 :

{

StatusBar1-Panels-Items[0]-Text = "Hello C++";

c.Brush-Style = bsClear;

TRect temp = Rect;

temp.Top += 1;

temp.Left += 1;

c.Font-Color = clWhite;

DrawText(c.Handle, Panel-Text.c_str(), -1,(RECT*)&temp, DT_SINGLELINE | DT_CENTER);

c.Font-Color = clBlack;

DrawText(c.Handle, Panel-Text.c_str(), -1, (RECT*)&Rect, DT_SINGLELINE | DT_CENTER);

break;

}

case 1:

{

c.Brush-Color =

clYellow;

c.FillRect(Rect);

c.Font-Color = clRed;

DrawText(c.Handle,"clYellow Color", -1, (RECT*)&Rect, DT_SINGLELINE | DT_CENTER);

break;

}

case 2:

{

Graphics::TBitmap* bm = new Graphics::TBitmap;

bm-Handle = LoadBitmap(NULL, MAKEINTRESOURCE(32760));

c.Draw(Rect.Left, Rect.Top, bm);

delete bm;

break;

}

}

}

BACK

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有