C# 隱性指標 [C# Implicitly pointer] VS C++ 傳統指標

C# 隱性指標 [C# Implicitly pointer] VS C++ 傳統指標

C# 隱性指標 [C# Implicitly pointer] VS C++ 傳統指標

GITHUB: https://github.com/jash-git/CS_-Implicitly_pointer

C#當建立一個空物件,然後用指定方式賦予值時,則新物件會是以指標和原物件共想成員變數空間

C#版:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CS_test
{
    public class A
    {
        public int m_inta,m_intb;
        public A()
        {
            m_inta=0;
            m_intb=0;
        }
        public A(int a,int b)
        {
            m_inta=a;
            m_intb=b;
        }        
    }
    class Program
    {
        static void pause()
        {
            Console.Write("Press any key to continue ...");
            Console.ReadKey(true);
        }
        static void Main(string[] args)
        {
            A a = new A(100, 200);
            A b;
            System.Console.Write(a.m_inta + "\t" + a.m_intb + "\n");
            //未初始化b所以不能使用 System.Console.Write(b.m_inta + "\t" + b.m_intb + "\n");
            System.Console.Write("---------------\n");
            b = a;
            System.Console.Write(a.m_inta + "\t" + a.m_intb + "\n");
            System.Console.Write(b.m_inta + "\t" + b.m_intb + "\n");
            System.Console.Write("---------------\n");
            b.m_inta = 200;
            b.m_intb = 100;
            System.Console.Write(a.m_inta + "\t" + a.m_intb + "\n");
            System.Console.Write(b.m_inta + "\t" + b.m_intb + "\n");
            System.Console.Write("---------------\n");
            pause();

        }
    }
}

C++版:

#include <iostream>

using namespace std;
class A
{
    public:
        int m_inta,m_intb;
        A()
        {
            m_inta=0;
            m_intb=0;
        };
        A(int a,int b)
        {
            m_inta=a;
            m_intb=b;
        };
};
int main()
{
    A a(100,200),b;
    cout << a.m_inta<<"\t"<< a.m_intb<< endl;
    cout << b.m_inta<<"\t"<< b.m_intb<< endl;
    cout << "----------------------" << endl;
    b=a;
    cout << a.m_inta<<"\t"<< a.m_intb<< endl;
    cout << b.m_inta<<"\t"<< b.m_intb<< endl;
    cout << "----------------------" << endl;
    b.m_inta=200;
    b.m_intb=100;
    cout << a.m_inta<<"\t"<< a.m_intb<< endl;
    cout << b.m_inta<<"\t"<< b.m_intb<< endl;
    cout << "~~~~~~~~~~~~~~~~~~~~~~" << endl;
    cout << "~~~~~~~~~~~~~~~~~~~~~~" << endl;

    A *pa;
    cout << a.m_inta<<"\t"<< a.m_intb<< endl;
    cout << pa->m_inta<<"\t"<< pa->m_intb<< endl;//未初始化,內容不可控
    cout << "----------------------" << endl;
    pa=&a;
    cout << a.m_inta<<"\t"<< a.m_intb<< endl;
    cout << pa->m_inta<<"\t"<< pa->m_intb<< endl;
    cout << "----------------------" << endl;
    pa->m_inta=200;
    pa->m_intb=100;
    cout << a.m_inta<<"\t"<< a.m_intb<< endl;
    cout << pa->m_inta<<"\t"<< pa->m_intb<< endl;
    cout << "----------------------" << endl;
    return 0;
} 


發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *