- C编译器支持#include <sub2.c>,后缀名不重要,因为linux里边根本不在意后缀名。
class Person{
public:
Person(int _age)
{
age=_age;
cout<<"Person"<<endl;
}
Person(const Person &_person)
{
age=_person.age;
cout<<"PersonPerson"<<endl;
}
operator=(const Person &_person)
{
age=_person.age;
cout<<"operator="<<endl;
}
~Person()
{
cout<<"~Person"<<endl;
}
public:
int age;
};
void fun(Person _lp)
{
cout<<_lp.age<<endl;
}
Person fun1()
{
Person person(40);
return person;
}
int main(){
Person person1(10);
person1 = Person(20); //产生了一个临时对象,用到了赋值运算符,随后立即释放临时对象
person1 = 20; //与上同理:person1 = Person(20);只是隐式调用了构造函数,生成临时对象
//cout<<person1.age<<endl;
fun(person1); //使用拷贝构造函数,借由person1,构造fun函数里使用的对象_lp
//下面两行代码其实也被编译器优化了,实际上是先产生临时变量,后调用拷贝构造
//g++ -fno-elide-constructors -c $< -o $@ -I ./inc
//禁用该优化
fun(Person(30)); //使用构造函数,生成临时变量,此临时变量直接就是_lp,不再额外进行拷贝构造得到_lp
fun(30); //与上fun(Person(30)) 同理,只不过这是构造函数的隐式调用
//理论上下面两行,按cpp plus5 上的说法,返回的值用于初始化调用点的一个临时变量·但执行结果比较意外,猜测是编译器
//进行了优化
//经验证,确实存在编译器优化,即返回值优化,使用指令:
//g++ -fno-elide-constructors -c $< -o $@ -I ./inc
//得到现象与书上一致
person1 = fun1(); //结果与person1 = Person(20);一样 函数返回时,并未从新创建新的对象,相当与使用的还是函数里边的局部对象
fun(fun1()); //结果和fun(Person(40));一样
system("pause");
return 0;
}
C++成员释放顺序
#include <iostream>
using namespace std;
class Dog{
public:
~Dog()
{
cout<<"~Dog"<<endl;
}
public:
int age;
};
class Pig{
public:
~Pig()
{
cout<<"~Pig"<<endl;
}
public:
int age;
};
class Person{
public:
Person(int _age):age(_age)
{
cout<<"Person"<<endl;
}
~Person()
{
cout<<"~Person"<<endl;
}
public:
int age;
Dog dog;
Pig pig;
};
int main(){
{
Person p1(40);
}
system("pause");
return 0;
}
先析构,再释放成员(因为析构函数里边也要使用成员变量),需要注意成员释放的顺序
4.
测试局部的字符串是怎样放入栈中的:
#include <iostream>
#include <sub1.h>
using namespace std;
int main(){
int a=6;
int b=9;
int c=0;
char str[] = "AB";
return 0;
}