1

I have a snippet of code that similar to the way of implementing smart pointer in C++.

template <class T>
class WrapObject
{
public:
    WrapObject(T* data)
    {
        _data = data;
    }
    T* operator->()
    {
        return _data;
    }
private:
    T* _data;
};

class Hello
{
public:
    void sayHello()
    {
        std::cout << "hello world" << std::endl;
    }
};


int main() {
    Hello h;
    WrapObject<Hello> wh(&h);
    wh->sayHello();
    return 0;
}

in main function, we can access to all methods of Hello object directly from WrapObject using operator '->'.

is there any way to do thing like this in C# or Java??

van con Nguyen
  • 101
  • 1
  • 5
  • 3
    Java: [No](http://stackoverflow.com/questions/1686699/operator-overloading-in-java). C#: [Maybe](https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx) – Tibrogargan Apr 27 '17 at 03:04
  • Not exactly, look into java reflection to see if you can get what you need to do through its method accessors. – Jason K. Apr 27 '17 at 04:15

1 Answers1

0

C# type divided into the 'value type' and 'reference type'

reference type (such as class,interface) like the pointer in C++ ,values save in the heap ,stack save the heap's address .

value type(such as int,long,char,struct) save on the stack .

C# only the value type supports pointer operations (you must set 'allow unsafe code' in your project). in C# you can't let the reference type be allocated on the stack.you can simply think that the reference type is a pointer

    public class MyClass
    {
        public string name { get; set; }
    }

    public struct MyStruce
    {
        public string name { get; set; }
    }   

    static void Main()
    {
        //MyClass *myClass=new MyClass()
        //*myClass->name="Lee";
        MyClass myClass = new MyClass();            
        myClass.name = "Tom";

        //MyStruce myStruce;
        //myStruce.name="Jack";
        MyStruce myStruce = new MyStruce();
        myStruce.name = "Jack";
    }

your code change to C# is

    public class WrapObject<T>
    {
        private T _data;
        public WrapObject(T data)
        {
            _data = data;
        }

        public T Data
        {
            get { return _data; }
        }
    }

    public class Hello
    {
        public void SayHello()
        {
            Console.WriteLine("hello world");
        }
    }

    static void Main()
    {
        Hello h = new Hello();
        WrapObject<Hello> wh = new WrapObject<Hello>(h);
        wh.Data.SayHello();
    }