C、C++: 引用、指针、实例、内存模型、namespace

// HelloWorld.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "string.h"
#include "iostream.h"
/** * 在C、C++语言中 * 声名语句中: 声明指针变量用*,声明变量或者常量都不加*。 * 譬如函数声明中的参数,返回值类型等。例如类中的字段的声明。 * 在赋值语句中: * 表示取值。 &表示取变量的地址,也就是取指针。 * * class,struct,unit: 也遵循上述原则。另外, * 在使用指针进行变量的访问、方法的调用时,要使用 -> * 在使用实例进行变量的方式、方法的调用时,要使用. * 例如personTest()方法中: * p是指针,*p就是p所指向的实例。 * * personTest()测试中的内存模型: * 指针p Value *p ,也可以称为实例 * ___________ __________ ___________ * | | | name |-------> |Fang JiNuo | *name * | | —————> | age : 23 | |___________| * |___________| | address | ______________________ * |__________|-------> | Bei Jing, Haid Dian | *address * |_____________________| */ class Person { private: char* name; int age; char* address; public : char* toString() { char* ret=name; return ret; } void setAge(int age){ this->age=age; } void setAddress(char* address){ this->address=address; } void setName(char* name){ this->name=name; } }; void personTest(){ Person * p=new Person(); p->setAddress("Bei Jing, Hai Dian"); // 采用指针的方式赋值 (*p).setName("Fang JiNuo"); // 采用对象的方式赋值 (*p).setAge(23); printf("show info: %s ", (*p).toString()); } void switchTest(){ int a=23; int b=1; int c=0; char oper='+'; switch(oper){ case '+': c=a+b; case '-': c=a-b; break; case '*': c=a*b; break; } printf("c = %d %c %d = %d", a, oper, b, c); } /** * C 语言的输入输出 */ void input_Output_test_c(){ printf("Hello World! "); printf("zhang san, wo cao "); int a,b; printf("input tow int number, pattern is d, d: "); scanf("%d, %d", &a, &b); printf("a is %d ",a); printf("b is %d ",b); printf("a+b=%d ",a+b); }

/**
 * C++ 的输入输出
 * 使用前需要include iostream.h
 */
 void input_Output_test_cpp()

 {

     // << out1 << out2 << out3 << out4 << endl;
     // endl 代表endline,也就是换行
     char * content=new char;
     cout << "plese input:" << endl;
     cin>> content;
     cout << content << endl;
  }



/**
 * namespace
 * C 语言不支持。
 * C++ 支持。
 *
 */
  namespace MyNS
  {
    void namespaceTest(){
      cout << "MyNS namespace invoked" << endl;
    }
  }


  void namespaceTest(){
    cout << "current namespace invoked" << endl;
  }

int main(int argc, char* args[])
{

// input_Output_test_c();
// personTest();
// switchTest();
// input_Output_test_cpp();
namespaceTest();
MyNS::namespaceTest();

    return 0;
}
原文地址:https://www.cnblogs.com/f1194361820/p/4802872.html