您的位置:首页 > 编程语言 > C语言/C++

C++中先于main执行

2016-04-15 11:11 489 查看
在C++中实现先于main执行:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <list>
#include <vector>
using namespace std;

typedef struct _info
{
int x;
int y;
_info& operator=(const _info& infoOther)
{
x = infoOther.x;
y = infoOther.y;
return *this;
}

bool operator ==( const _info& info2)
{
return (x == info2.x) && (y == info2.y);
}

}info;

void add2(int& x, int& y)
{
//cout<<"add2 : "<< *x + *y <<endl;
x = x + y;
y = x - y;
x = x - y;
}

int add(int x, int y)
{
cout<< x << " add " << y<<endl;
return x+y;
}

int result = add(1,1);

class Base
{
public:
Base()
{
cout<<"base here!"<<endl;
}
};

Base myBase;

int main()
{
cout<<"this is the main begin!"<<endl;
cout<<"the add result is " <<result<<endl;

info myInfo = {0};
info myCopyInfo = {0};
myInfo.x = 1;
myInfo.y = 2;

myCopyInfo = myInfo;

cout<<"myCopyInfo.x = " <<myCopyInfo.x<<endl;
cout<<"myCopyInfo.y = " <<myCopyInfo.y<<endl;
bool result = (myInfo == myCopyInfo);

cout<<"the result of < is "<<result<<endl;

int x1 = 1;
int y1 = 2;

add2(x1, y1);
printf("x1 = %d \n", x1);
printf("y1 = %d \n", y1);
return 0;
}

从上面的代码中可以看到类Base的对象myBase先于main执行。

1 add 1

base here!

this is the main begin!

the add result is 2

myCopyInfo.x = 1

myCopyInfo.y = 2

the result of < is 1

x1 = 2

y1 = 1

Press any key to continue . . .

同时引用他人的文章:

以前在提供给客户的接口库中如果是dll,则dll中的互斥锁很容易在dllmain中初始化,

但是对于lib静态库则没有想到更好的处理办法。现在才发现原来可以在lib中也可以简单直

接的在main函数外初始化。大家有这方面更深一步的研究,希望能共享一下,多谢!

1、vs2010下,编译为可执行程序(注意运行顺序):



2、编译为静态库被调用(注意运行顺序):



3、编译为动态库被调用(注意运行顺序):



相关现象1:直接在项目-》属性-》链接器-》高级-》入口点中定义为main,程序编译过程中警告,



运行后,add函数并没有先于main函数执行



入口点改为add,仍然会有警告:



运行后a+b值为随机



由此可以看出  此时vs入口点“并不是”或者“并不能说”是 main 或者add。

使用OD更进一步的跟踪:在1情况下,在_tmaincrtstartup函数中会在进行堆变量初始化时直接调用add函数,在调用add函数后才会再进行main函数调用。
结构体重载:
#include "stdafx.h"
#include <iostream>
using namespace std;

template <typename T>
void DisplayValue(T value)
{
cout<<value<<endl;
}

struct Currency
{
int Dollar;
int Cents;

Currency& operator=(Currency& value)
{
Dollar = value.Dollar;
Cents = value.Cents;
return *this;
}
Currency& operator+(Currency& value)
{
Dollar += value.Dollar;
Cents += value.Cents;
return *this;
}
Currency &operator-(Currency& value)
{
Dollar = Dollar - value.Dollar;
Cents = Cents - value.Cents;
return *this;
}
Currency& operator*(Currency& value)
{
Dollar *= value.Dollar;
Cents *= value.Cents;
return *this;
}
friend ostream &operator<<(ostream &out,Currency value);
};

ostream& operator<<(ostream &out,Currency value)
{
out<<"The dollar = "<<value.Dollar<<" and The Cents = "<<value.Cents<<endl;
return out;
}
int _tmain(int argc, _TCHAR* argv[])
{

Currency c1;
c1.Dollar = 10;
c1.Cents = 5;
DisplayValue(c1);
Currency c2,c3;
c2 = c1;
c3= c1+c2;
DisplayValue(c3);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: