#ifndef _TEST_H #define _TEST_H #include <iostream> #include <string> using namespace std; int x = 5; struct s { public: s(const s&) { a = 1; cout << "copy constructor" << endl; } s() { a = 0; cout << "Initialize" << endl; } ~s() { cout << "Destructor" << endl; } void func1(s& test){ cout << &test; test.a = 4; //test = s1; }; public: int a; }; s makes() { s s1; cout << &s1 << endl; return s1; } string foo() { return "hello"; } void bar(string&) { } void fa(s &sss) { sss.a = 0; } struct Int { Int(int i):i_(i){} Int& operator+(/*const*/ Int& rhs) //参数是+号的右值 { i_ += rhs.i_; return *this; } int i_; }; Int foo (int x, int y) { //如果编译器符合标准,那么就不可能通过编译 //Int(y)返回的是一个临时对象,因为临时对象是不能作为左值的, //临时对象不能赋值给非const的引用 return Int(x) + Int(y); } class A { public: int i; A(int a):i(a){cout << "A(int) " << endl;} A& operator++() { i++; return *this; } }; void fun(A&){} struct M{}; struct B { public: B(){} B(M& a){} }; struct B1 : public B { public: B1(/*const*/ B& b) : B(b) {} }; void main() { //这个例子说明在进行类型转换的时候还是会生成const临时变量的,这个 //是符合c++标准的 //M a; //B1 b1(a); //对于这两个例子,网上说是不应该编译通过的,但是在vs2008中编译通过了 //这说明这个是编译器相关的,vs2008可能做了相关的操作或优化 //但是c++标准说:如果编译器完全支持c++标准,则这个是通不过编译的 //fun(A(1)); //cout << foo(5,6).i_ << endl; /* //考察变量的作用域 //int x = x;//编译报错,使用时候未初始化 int x = ::x; cout << x << endl; //printf("&d",x); */ //wprintf和printf的区别wchar_t类型 /* wchar_t wch[] = L"helloworld"; printf("%s\n",wch); wprintf(L"%s\n",wch); */ /* //printf和cout是以\0(NULL)标识一个字符串输出结束标识符 char ch[] = "hello\0world"; cout << ch << endl; printf("%s\n",ch); */ /* //这里注意引用和赋值的作用不同,赋值就是拷贝一个副本出来 int a = 1; const int& b =a; //an convert from int to const int const int aa =2; int& bb = aa; //cannot convert from const int to int */ /* //无论是从书上还是网上查到的,都是说c++如果函数按值返回会产生一个 //临时对象并且这个对象是const类型的。但是像下面这样来验证的话发现 //并不是如此,分析后认为:要么这样用到的不是返回的临时对象,但是 //单步调试之后认为可以排除这种情况;要么是临时对象不是const类型的; //要么就是编译器在使用这个临时变量做参数的时候进行了一定的操作( //因为如果是显式给一个const类型的参数的话是编译通不过的)。 //const类型不能被赋为非const类型的值;也不能引用为非const类型的变量。 bar(foo()); //bar("hello world"); //makes(); //生成了临时变量,但是没有想到验证临时对象是否是const类型的方法 //s s1 = makes(); //编译器优化了,不产生临时变量,编译器相关的 //makes().a = 3; //makes().func1(makes()); fa(makes()); const s as; //fa(as);//编译报错,因为无法将const类型用非const类型来引用 */ //从下面这行代码可以看出,编译器是做了优化的,这个时候应该是 //要么没有生成临时对象,要么临时对象不是const类型的 //这样没有生成临时对象 //s &s2 = makes(); //cout << &s2 << endl; //s s4 = makes(); //cout << &s4 << endl; //这样生成了临时对象,但是不是const类型的,应该是编译器相关的结果 s s3; makes() = s3; printf("\n"); } #endif //_TEST_H