c++语言的一些点

文章目录[x]
  1. 0.1:初始化和赋值
  2. 0.2:列表初始化
  3. 0.3:默认初始化
  4. 0.4:声明与定义的关系
  5. 0.5:引用和指针
  6. 0.6:const限定符

初始化和赋值

初始化不是赋值,是创建变量时赋予其一个初始值,而赋值是把对象的当前值擦除,以一个新值来替代。

列表初始化

int x = { 0 };
int x{0};

当用于内置类型的变量时,如果使用列表初始化且初始值存在丢失的风险,则编译器将报错。

long double ld = 3.1415926;
int a{ld}, b = {ld};//错误
int c{ld}, d = ld;//正确

默认初始化

定义于任何函数体之外的内置类型变量被初始化为0,定义在函数体内部的内置类型变量将不被初始化。

每个类各自决定其初始化对象的方式。如果没有显式的初始化,则其值由类确定。

声明与定义的关系

声明使得名字为程序所知,一个文件如果想要使用别处的名字则必须包含对那个名字的声明。而定义负责创建与名字相关联的实体。

他们都规定了变量的类型和名字。除此之外,定义还申请存储空间,也可能会为变量赋一个初始值。

extern int i;//声明而非定义i
int j;//声明并定义j

任何包含显式初始化的声明即成为定义。

在函数体内部,如果试图初始化一个由extern关键字标记的变量,将引发错误。

变量能且只能被定义一次,但是可以被多次声明。

引用和指针

引用为对象起了另一个名字

int ival = 1024;
int &refVal = ival; //refVal指向ival,是ival的另一个名字
int &refVal2;       //错误,引用必须初始化

定义引用时,程序把引用和它的初始值绑定在一起,而不是将初始值拷贝给引用。因为无法令引用重新绑定到另外一个对象,因此引用必须初始化。

定义一个引用后,对其进行的所有操作都是在与之绑定的对象上进行的。

因为引用本身不是一个对象,所以不能定义引用的引用。

指针本身就是一个对象,允许对指针进行赋值和拷贝。

指针无需在定义时赋值,在块作用域内定义的指针如果没有被初始化,也将拥有一个不确定的值。

指针存放某个对象的地址,要想获取该地址需要用取地址符:

int ival = 42;
int *p = &ival; //p存放变量ival的地址,或者说p是指向变量ival的指针

因为引用不是对象,没有实际地址,所以不能定义指向引用的指针。

指针的类型要和它所指向的对象严格匹配。

指针的值应属于下列4种状况之一:

1.指向一个对象

2.指向紧邻对象所占空间的下一个位置

3.空指针,意味着指针没有指向任何对象

4.无效指针,上述情况之外的其他值

int ival = 42;
int *p = &ival;
cout << *p;  //通过解引用符*得到指针p所指的对象,输出42

*p = 0;      //由符号*得到指针p所指的对象
cout << *p;  //输出0

几个生成空指针的方法:

int *p1 = nullptr;
int *p2 = 0;
//需要首先#include cstdlib
int *p3 = NULL;

指向指针的指针:

int ival = 1024;
int *pi = &ival;
int **ppi = &pi;  //ppi指向一个int型的指针

指向指针的引用:

int i = 42;
int *p;
int *&r = p;//r是一个对指针p的引用

r = &i;  //令p指向i
*r = 0;  //将i的值改为0

const限定符

const对象一旦创建后其值就不能改变,所以const对象必须初始化。

用一个对象去初始化const对象时,它是不是const无关紧要。

默认状态下,const对象仅在文件内有效。

要想只在一个文件中定义const,而在其他多个文件中声明并使用它,解决办法是,对const对象不管是声明还是定义都添加extern关键字,这样只需要定义一次就行:

//file_1.cc定义并初始化了一个常量,该常量能被其他文件访问
extern const int bufSize = fcn();
//file_1.h头文件
extern const int bufSize;//与file_1.cc中定义的bufSize是同一个

在初始化常量引用时允许用任意表达式作为初始值,只要该表达式的结果能转换成引用的类型即可。

decltype使用的表达式是变量时,返回变量类型,不是,则返回表达式结果对应的类型。

点赞
  1. 传哥爸爸说道:

    :hehe: 给传哥生猴子

    1. Eusebio说道:

      Good crew it's cool :) plavix medicine price In 23 of the countries surveyed, most say China already has or will soon replace the United States as the top superpower. In only six countries, it was the consensus that China would never replace the United States.

    2. Stephen说道:

      Have you got any qualifications? accutane 60 mg results "South Korea will need to decide on a plan as soon as possible in order to secure (the project's) budget for next year," said one source with direct knowledge of a task force set up last month to review options for the delayed fighter jet buy.

      1. Alfred说道:

        My battery's about to run out chrysin benefits skin "Only the rich have time for such debates," he replied. "Nobody would want want to live here but we have no choice - whether you call it a slum or not makes no difference to us as it is not going to change our lives."

      2. Fausto说道:

        I've just graduated voltaren xr 100mg reviews The next great challenge for the mathematical modellers is to come up with a working version of the brain, with its billions of interconnected neurons. Last week, a model of the world’s smallest brain – that of a 1mm-long nematode worm, C. elegans, containing just 302 neurons – went on show at MOSI (the Museum of Science & Industry in Manchester). Meanwhile, the Human Brain Project, led by Prof Henry Markram at the École Polytechnique Fédérale de Lausanne on the shores of Lake Geneva, passed a key milestone last September, with a proof of concept that showed it could wire up virtual neurons in a way that matches what’s been observed in studies of living nerve tissue.

      3. Salvador说道:

        Could I order a new chequebook, please? boniva.com
        The last original drama from BBC Four shows us what we will be missing with William Ivory’s (Women in Love and, on the big screen, Made in Dagenham) entertaining and tightly composed biopic about the final reunion between Richard Burton and Elizabeth Taylor (expertly played by Dominic West and Helena Bonham Carter) for a production of Noël Coward’s Private Lives in Boston and then on Broadway in 1983.

      4. Kasey说道:

        Just over two years generic for prevacid 30 mg Sad day in America when Republicans care more about their Tea Party agendas than about the millions of Americans (The People) their selfish, arrogant actions are harming.  Get rid of Obamacare?  Then please Republicans how are the majority of Americans who are not well off can afford health care?  Republicans should save their vendettas in attacking Obama for another day, so they won't affect The People.  Imagine traveling across the country to Washington D.C. to visit the Smithsonian museums and the national monuments to see everything close, or finally making it to Yosemite or Yellowstone to see the gates closed or being told you have 48 hours to leave if you were lucky to get in.  I hope America remembers this in 2016 and vote people like Boehner and his buddies out of office and their Good Ol' Boys Club.

      5. Renato说道:

        What line of work are you in? usmedicalsupplies.com complaints Rodriguez had flyouts in the first, second and fifth innings and grounded out in the seventh. His drive to center field in the second was a sacrifice fly and he said “driving the ball to the outfield in the air is always a good sign for me versus a ground ball . . . I’m trying to eliminate ground balls to the left side of the infield.”

    3. Herman说道:

      I'd like , please seroquel xr dose for sleep The 71-year-old Fox, whose election in 2000 for the conservative National Action Party (PAN) ended seven decades of one-party rule in Mexico, worked closely with the United States during his time in office to combat Mexican drug gangs.

      1. Antonia说道:

        Other amount zovirax 800 mg uses IOC's share sale, expected to fetch about 40 billion rupees,was set for this month. The finance ministry had lined upinvestor roadshows in Asia, Europe and the United States, butjust as officials were packing their bags early this month, theoil ministry pulled out at the last minute. The finance ministrylearnt of the pull-out from TV news channels.

      2. Riley说道:

        About a year fosamax prescription His intervention adds weight to growing calls for an overhaul of UK drug policy. Leading figures in health, including England’s chief medical officer Dame Sally Davies, have called for drug addiction to be viewed primarily as a medical, not a criminal, problem. The Deputy Prime Minister Nick Clegg and the influential Home Affairs Select Committee have both backed calls for a Royal Commission to look at options for reform.

      3. Allan说道:

        I can't get through at the moment cipro and ice cream Rappers and fans alike have taken the obvious next step in this great debate: to the Twitter battlefield! There's a lot of ... let's say, "colorful" language used that Social Climber doesn't deem fit to publish in this space.

        1. Riley说道:

          Have you got any experience? iv cytoxan myeloma "By now, I suppose we know better than to predict that Prop 8 proponents will actually give up their fight," San Francisco City Attorney Dennis Herrera said. "But it's certainly fair to say that their remaining legal options are increasingly absurd."

        2. Emmett说道:

          I support Manchester United amoxicillin 500 dosage for toothache After that, oil and other markets could be very volatile forthe next few weeks because of a huge backlog of data such asemployment numbers that have been held up because of theshutdown of the U.S. government.

        3. Elias说道:

          Not in at the moment where could i get clomid Meyer, who turned 49 Wednesday, answered critics of his oversight while at the school, saying in a recent statement to the Dispatch and the Gainesville Sun: "Relating or blaming these serious charges to the University of Florida, myself or our staff is wrong and irresponsible."

        4. Malcolm说道:

          Withdraw cash novartis coupons for trileptal
          IQE shares were up 9 percent at 28 pence in early trade onthe London Stock Exchange. They have fallen 27 percent sinceQualcomm Inc unveiled plans in February for a productthat could pose a threat to IQE's semiconductors.

        5. Jacob说道:

          I'll put him on revatio sclerodermia Orr's plan, laid out in a June 14 proposal to creditors,lumped voter-approved unlimited tax general obligation bondswith less-secured debt, pensions and unfunded retiree healthcare liabilities. All would be offered just pennies on thedollar.

        6. Tony说道:

          We went to university together kamagra with paypal "... The business is going to come back and there is noreason to be in a great rush to do anything," Chief ExecutiveSeifi Ghasemi said, but added that the company was committed toselling the business.

        7. Alvaro说道:

          We were at school together harga griseofulvin 500 mg As a trained scientist, Elisa can think of only two explanations: she’s either experienced some kind of psychotic break (though she feels fine) or she’s been zapped into a parallel universe. She must navigate her way through this alternate existence as though through a computer game. Her mission is to find out who she is; and what responsibility she must assume for the state of her family and her future.